簡體   English   中英

在單詞中間分割字符串

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM