簡體   English   中英

append java中帶前綴和后綴的句子怎么寫?

[英]How to append a sentence with prefix and suffix in java?

我正在嘗試讀取包含以下內容的輸入文件:

輸入.txt

Hello world. Welcome,
to the java.

而且,我必須 append 帶有前綴(BEGIN)和后綴(END)的句子和 output 應該如下所示:

output 預計:

BEGIN_Hello world_END.BEGIN_ Welcome,
to the java_END.

以下是我讀取 function 的輸入文件。 我正在讀取整個文件並將其存儲在數組列表中: InputDetails.java

private List<String> readInput = new ArrayList<>();
public void readFile() throws IOException {
   while((inputLine = input.readLine()) != null ) {
      readInput.add(inputLine);
   }
}

//Getter to return input file content
public List<String> getReadInput() {
   return readInput;
}

以下是我用BEGINEND附加字符串的代碼:

public void process() {
   InputDetails inputD = new InputDetails();
   for(int i=0;i<inputD.getReadInput().size();i++) {
            String sentence = inputD.getReadInput().get(i);
            String splitSentence[] = sentence.split("\\.");
            for(int j=0;j<splitSentence.length;j++) {
                System.out.println(splitSentence[j]);
                splitSentence[j] = "BEGIN_"+splitSentence[j]+"__END";
            }
            sentence = String.join(".",splitSentence);
            inputD.writeToFile(sentence);
        }
}

output 得到:

BEGIN_SENTENCE__Hello world__END_SENTENCE.BEGIN_SENTENCE__Welcome
to the java.

注意:每個句子用“.”分隔。 (句號)字符。 output 語句應以 BEGIN_ 為前綴,以 __END 為后綴。 句點字符不被視為句子的一部分。 並且,輸入文件由一個或多個空格分隔。 當它有句號時,句子是完整的(。)即使這意味着句子在新行上完成(就像我上面指定的輸入一樣)。 所有,特殊字符 position 應保留在 output 中。 句號(.) 或逗號(,) 與單詞之間也可以有空格。 例如: java。 或歡迎,

誰能幫我解決這個問題? 謝謝

首先,您需要將字符串列表輸入連接到單個字符串中。 然后,您可以使用String.split()方法將輸入分解為由. 特點。 然后,您可以選擇在該數組上運行循環或使用 stream 方法(如下所示)來迭代您的句子。 在每個部分,只需 append 所需的BEGIN__END塊到句子。 您可以使用+運算符手動連接字符串,也可以使用帶有String.format()的字符串模板(如下所示)。 最后,重新引入. 分隔符用於通過將部分連接回單個字符串來中斷輸入。

String fullString = String.join("", getReadInput());
Arrays.asList(fullString).split("\\.")).stream()
  .map(s -> String.format("BEGIN_%s_END", s))
  .collect(Collectors.joining("."));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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