2015-10-18 57 views
0

我想查找一個字符串是否包含空格,並且是否打印出錯誤。一旦找到空格,我必須使用substring()打印出一行之前的空格之前的所有內容,以及第二行之後的空格。這是我曾嘗試:查找一個字符串是否包含「」

while (type.hasNext()) 
{ 
     String word = type.nextLine(); // save the word that is tped into variable 'word' 

     String nextLine = word; // save the 'word' as variable 'nextLine' 

     String check = " "; //save the white space that is typed as 'check' 

     int space = check.indexOf(' '); //check the index of space 


     if (word.contains(" ")) 
     { 
      System.out.println(word); 

      String test = check.substring(0, space); 

      System.out.println(word); 

      String test2 = check.substring(space, word.length()); 

      System.out.println(word); 

     } 

     else 
      System.out.println("ERROR: There is no space!"); } 

感謝您的幫助

+2

'String.contains(字符串序列);'' – 3kings

回答

2

它是如此簡單:

String.contains(" "); [where String is the name of your String variable]. 

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence)

+0

包含(」「)'是一個字符串搜索,並且不爲'的indexOf(」「)作爲高效= -1',其!是一樣容易寫和理解。 – Andreas

+0

@Andreas不,它不是...公共布爾包含(CharSequence s){ return indexOf(s.toString())> -1;}這是直接從字符串類的Java源代碼.. – user2494817

+1

你錯過了indexOf('')'和'indexOf(「」)'之間的區別。首先是*字符*搜索,它比第二個字符的* substring *搜索效率更高。 – Andreas

1

這不是如何indexOf()作品。你有沒有read the documentation?

返回: 在此對象表示的字符序列上的字符中第一次出現的索引,或者-1,如果字符不會發生。

if (check.indexOf(' ') < 0) 
{ 
    System.out.println("ERROR: There is no space!"); 
} 
相關問題