2015-10-18 108 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!"); 
} 
相关问题