简体   繁体   English

如何检查数组中是否包含带空格的单词?

[英]How do i check if my array contains a word that has spaces in it?

int num;
num = in.nextInt();
String array[] = new String[num];
for (int i = 0; i < num; i++) {
    array[i] = in.next();
    if (array[i].equals("hey guys"))
        System.out.println("hey guys");
    else
        System.out.println("buzz");
}

This is the code i tried. 这是我尝试的代码。 When i remove the space in "hey guys", it works allright but otherwise it doesn't. 当我删除“嘿家伙”中的空格时,它可以正常工作,但否则不起作用。

Just use in.nextLine() instead of in.next(). 只需使用in.nextLine()而不是in.next()。 It will take line input including spaces. 这将需要包括空格在内的行输入。

int num;
num = in.nextInt();
String array[] = new String[num];
for (int i = 0; i < num; i++) {
    array[i] = in.nextLine();
    if (array[i].equals("hey guys"))
        System.out.println("hey guys");
    else
        System.out.println("buzz");
}

You can use contains() method from String class to check if the string has spaces in it.But from what I understood,you are facing the issue while reading the string with spaces.You should read in using in.nextLine() 您可以使用String类中的contains()方法检查字符串中是否包含空格。但是据我了解,您在读取带空格的字符串时遇到了问题。您应该使用in.nextLine()进行阅读

int num;
num=in.nextInt();
String array[]=new String[num];
for(int i=0;i<num;i++){
array[i]=in.nextLine();
if(array[i].contains(" "))
//contains space
else 
System.out.println("buzz");}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM