[英]Splitting a string in the middle of a words issue
我已经通过从csv获取字段数据来自动完成了从网站填写表格的流程。
现在,该地址的形式为3个字段:
地址1 ____________
地址2 ____________
地址3 ____________
每个字段限制为35个字符,因此每当我到达35个字符时,我都会在第二个地址字段中继续地址字符串...
现在,问题是我当前的解决方案将其拆分,但是如果str中的'barcelona'和'o'是第35个字符,那么如果它达到35个字符,它会立即将其切成35个字符,因此在地址2中将是“ na”。
在这种情况下,我想确定第35个字符是否在一个单词的中间,然后将整个单词带入下一个字段。
这是我目前的解决方案:
private def enterAddress(purchaseInfo: PurchaseInfo) = {
val webElements = driver.findElements(By.className("address")).toList
val strings = purchaseInfo.supplierAddress.grouped(35).toList
strings.zip(webElements).foreach{
case (text, webElement) => webElement.sendKeys(text)
}
}
我希望在此提供一些帮助,最好使用Scala,但java也可以:)
谢谢分配!
既然您说过您也将接受Java代码...下面的代码会将给定的输入字符串包装到具有给定最大长度的几行中:
import java.util.ArrayList;
import java.util.List;
public class WordWrap {
public static void main(String[] args) {
String input = "This is a rather long address, somewhere in a small street in Barcelona";
List<String> wrappedLines = wrap(input, 35);
for (String line : wrappedLines) {
System.out.println(line);
}
}
private static List<String> wrap(String input, int maxLength) {
String[] words = input.split(" ");
List<String> lines = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
for (String word : words) {
if (sb.length() == 0) {
// Note: Will not work if a *single* word already exceeds maxLength
sb.append(word);
} else if (sb.length() + word.length() < maxLength) {
// Use < maxLength as we add +1 space.
sb.append(" " + word);
} else {
// Line is full
lines.add(sb.toString());
// Restart
sb = new StringBuilder(word);
}
}
// Add the last line
if (sb.length() > 0) {
lines.add(sb.toString());
}
return lines;
}
}
输出:
This is a rather long address,
somewhere in a small street in
Barcelona
这不一定是最好的方法,但是我想无论如何您都必须使其适应Scala。
如果您更喜欢库解决方案(因为...为什么要重新发明轮子?),还可以查看Apache Commons的WordUtils.wrap() 。
英文单词由空格分隔(或其他标点符号,但在这种情况下不相关,除非您实际上要根据其来换行),并且有两种选择可利用此优点:
您可能要做的一件事是从字符串中获取35个字符的子字符串,使用String.lastIndexOf找出空格,然后仅将空格添加到地址行中,然后从该空格字符开始重复该过程直到您输入了字符串。
另一种方法(在Marvin的答案中展示)是仅在空格上使用String.split并将它们串联在一起,直到下一个单词将导致字符串超过35个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.