gpt4 book ai didi

java - java中要求用户输入不带空格的字符串

转载 作者:行者123 更新时间:2023-12-01 12:52:29 25 4
gpt4 key购买 nike

如果用户输入带有空格的字符串,我需要程序返回一条消息。例如“这是我的房子”是不允许的,“thisismyhouse”是允许的。现在我使用此代码来检查空格

    for(int i = 0; i < blabla.length(); i++) {
if (blabla.charAt(i) == ' ')
flag++;
}
}
if (flag != 0) {
System.out.println("input must not contain spaces");
}

我想知道是否有一个内置函数,如“blabla.equals”等用于此目的?或者更好的写法?

最佳答案

解决方案1:

if(input.contains(" "))
System.out.println("input must not contain spaces");

解决方案2:

if(input.indexOf(" ")>=0)
System.out.println("input must not contain spaces");

解决方案 3:

您可以简单地允许用户输入空格并自行删除它们:

 input = input.replaceAll(" ","");

关于java - java中要求用户输入不带空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24116510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com