我试图查找字符串是否包含空格,以及是否打印出错误。一旦找到空间,我必须使用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!"); }
感谢您的帮助
答案 0 :(得分:2)
就这么简单:
String.contains(" "); [where String is the name of your String variable].
答案 1 :(得分:1)
这不是indexOf()
的工作原理。你有read the documentation?
返回: 此对象表示的字符序列中第一次出现的字符的索引,如果未出现该字符,则为-1。
if (check.indexOf(' ') < 0)
{
System.out.println("ERROR: There is no space!");
}