2011-04-01 18 views

回答

34

如果字符串是在相同的程序構造,我會建議使用此:

String newline = System.getProperty("line.separator"); 
boolean hasNewline = word.contains(newline); 

但如果你specced使用\ N,該驅動程序說明要做什麼:

class NewLineTest { 
    public static void main(String[] args) { 
     String hasNewline = "this has a newline\n."; 
     String noNewline = "this doesn't"; 

     System.out.println(hasNewline.contains("\n")); 
     System.out.println(hasNewline.contains("\\n")); 
     System.out.println(noNewline.contains("\n")); 
     System.out.println(noNewline.contains("\\n")); 

    } 

} 

導致在

true 
false 
false 
false 

在效應初探到您的評論:

class NewLineTest { 
    public static void main(String[] args) { 
     String word = "test\n."; 
     System.out.println(word.length()); 
     System.out.println(word); 
     word = word.replace("\n","\n "); 
     System.out.println(word.length()); 
     System.out.println(word); 

    } 

} 

結果

6 
test 
. 
7 
test 
. 
+0

Works但s = s.replace(「\ n」,「\ n」);不會用新的行和空格替換新行。 – 2011-04-01 20:45:03

+0

是的。更新我的答案。它清楚地顯示了換行符後的空格。 – corsiKa 2011-04-01 20:47:59

7

第二個:

word.contains("\n"); 
+1

我試過,但它不工作 – 2011-04-01 20:29:07

+1

你可以解釋,爲什麼它不工作。你的意見是什麼?結果是什麼?預期的結果是什麼? – 2011-04-01 20:30:19

+0

對不起,我重建JAr後沒有重新啓動我的tomcat,所以它沒有生效。它現在雖然工作,儘管替換s = s.replace(「\ n」,「\ n」);不管用 。 – 2011-04-01 20:49:03

8

對於便攜性,你真的應該做這樣的事情:

public static final String NEW_LINE = System.getProperty("line.separator") 
. 
. 
. 
word.contains(NEW_LINE); 

,除非你是絕對肯定"\n"是你想要的。

相關問題