【问题标题】:Splitting a string in the middle of a words issue在单词问题中间拆分字符串
【发布时间】:2015-07-13 22:05:13
【问题描述】:

我已经通过从 csv 中获取字段数据来自动化一些从网站填写表单的流程。

现在,对于地址,表单中有 3 个字段:

地址 1 ____________

地址 2 ____________

地址 3 ____________

每个字段有 35 个字符的限制,所以每当我达到 35 个字符时,我都会在第二个地址字段中继续地址字符串...

现在,问题是我当前的解决方案将拆分它,但如果它达到 35 个字符,它会立即删除单词,如果 str 中的单词 'barcelona' 和 'o' 是第 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 也可以:)

感谢分配!

【问题讨论】:

  • 我会使用不同的方法:在空格上拆分以获得单个单词,然后将单词组合起来,只要总长度低于 35。
  • 我同意,但如果你能帮我写代码会有所帮助:) 只是,谢谢@Marvin
  • 我可以在java中发布代码吗?我不知道 scala 语法:P
  • @Marvin 那是确切的解决方案:)

标签: java regex scala


【解决方案1】:

既然你说你也接受 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。

如果您更喜欢图书馆解决方案(因为...为什么要重新发明轮子?)您也可以查看WordUtils.wrap() from Apache Commons

【讨论】:

    【解决方案2】:

    英语中的单词由空格(或其他标点符号,但在这种情况下是无关紧要的,除非你真的想以此为基础换行),并且有几个选项可以利用它来发挥你的优势:

    您可能会做的一件事是从您的字符串中获取一个 35 个字符的子字符串,使用 String.lastIndexOf 来确定空间的位置,然后只将该空间添加到您的地址行,然后重复该过程从那个空格字符,直到你输入了字符串。

    另一种方法(在 Marvin 的回答中展示)是在空格上使用 String.split 并将它们重新连接在一起,直到下一个单词会导致字符串超过 35 个字符。

    【讨论】:

    • "英文单词用空格分隔"或逗号、句号、分号、感叹号、问号,在某些情况下还有破折号
    • 没错,但大多数例子后面仍然有空格,作者可能不希望删除或将标点符号发送到下一行。
    • 当然。我只是一个语法书呆子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多