2014-01-19 38 views
11

我有一個具有來自文本區域的字符串:(變量名稱string n位於字符串中的位置在哪裏?

This is the first line 
And this is the second 

如果我使用string.split(" ")到拆分成單獨的單詞,然後檢查什麼話包含「\ n」

for(String s : string.split(" ")) { 
    if(s.contains("\n")) 
     System.out.println(s); 
} 

兩個lineAnd在我的句子包含\n。但是,如果我要檢查,如果字也開始\n或與它結束了,這讓我沒有結果。

if(s.contains("\n")) { 
    System.out.println("Contains"); 

    if(s.startsWith("\n")) 
     System.out.println("Starts with"); 
    else if(s.endsWith("\n")) { 
     System.out.println("Ends with"); 
    else 
     System.out.println("Does not contain"); 
} 

從我的結果:

Contains 
Does not contain 

所以,如果字包含\n,但沒有啓動或什麼時候結束,哪兒是它,我該怎麼管理它,而不使用replaceAll(String, String)

+0

我想新的生產線可表示爲'\ r \ N'您的系統上(Windows)。 – Crozin

+0

@Crozin在這種情況下''\ n''仍然是最後一個字符...... –

+0

'\ n'在空白類中,所以是「」。分割'\ s +'以獲得所有那些令人討厭的未知分隔符。不要依賴Split()默認的BS,如果它是半可移植的,不要依賴它。 – sln

回答

23

什麼情況是,該字符串的樣子:

"This is the first line\nAnd this is the second" 

所以,當你通過把它分解" "你:

"line\nAnd" 

當你打印出來,它看起來像兩個獨立的strings.To證明這一點,嘗試在for循環添加額外的打印:

for (final String s : string.split(" ")) { 
    if (s.contains("\n")) { 
     System.out.print(s); 
     System.out.println(" END"); 
    } 
} 

輸出:

line 
And END 

而當你嘗試檢查一個字符串是否開始或結束"\n"因爲事實上串"line\nAnd"不啓動或結束了,你不會得到任何結果

+0

'\ n'是一個空格! http://en.wikipedia.org/wiki/Whitespace_(programming_language) – MariuszS

+1

不是英語爲母語的人,「'」''的正確名稱是什麼? – Christian

+1

可能'空間':D http://en.wikipedia.org/wiki/Space_character – MariuszS

5

正是在這裏"line\nAnd"

當您打印本,它出來作爲

line 
And 
+0

所以你說'line'和'And'被看作是一個單詞,由\ n連接起來? –

+0

@VinceEmigh當然。你在空間上分裂,所以\ n不受影響。 – Ingo

+2

@VinceEmigh如果你想分割單詞,你應該使用'string.split(「\\ s +」)'。 – Njol

2

沒有。這是線\ NAND。你已經看到在控制檯:


正是由於換行符\ n的。

所以它的;在中,如果你改變了代碼s.contains("\n"))。你會看到它。

2

字符串:

This is the first line\nAnd this is the second 

" " (space)分開後你會得到作爲輸出:line\nAnd,所以這意味着字符串不啓動或\n結束。

if (s.contains("\n")) { 
    System.out.print(s); 
} 

輸出:

line 
And