[英]How do I replace all blank lines with “@”?
假設我有一個列表:
List<Strings> lines = new ArrayList<String>();
lines.add("one");
lines.add("");
lines.add("two three");
當我將其轉換為字符串即this.str
時,可以得到以下this.str
:
one
two three
我正在嘗試創建一種計算行數的方法,但是它無法識別空行。 我嘗試這樣做:
this.str = this.str.replaceAll("\n", "@");
String[] words = this.str.split("[\\r\\n]+");
如果我要打電話給System.out.println(Arrays.toString(words)
,我希望得到[one, @, two three]
,但是,我得到的卻是[one@@two three]
。這個?
實際上,輸出是正確的。
字符串str在單詞“ one”之后有兩個換行符。
one\n
\n
two three
正則表達式中的+ :
this.str.split("[\\r\\n]+");
表示一個或多個 。 關鍵是: 您在替換\\ n char后將其拆分! ,因此現在數組中只有一個字符串。
更改此:
this.str.split("[\\r\\n]+");
有了這個:
this.str.split("@");
this.str
實際上包含字符串: one\\n\\ntwo three
。 這就是執行后的原因:this.str = this.str.replaceAll(“ \\ n”,“ @”); this.str
現在包含:“ one @@ two three”。
@
的數量是您在this.str
擁有的新行的數量。 現在,如果您這樣做:
String[] words = this.str.split("@");
您將得到["one", "", "two three"]
,這是原始this.str
的行數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.