我正在开发的一个简单程序遇到了一些问题,我只需要问用户是要正常价格还是要出售价格。而且他需要以字符串值进行响应。现在我知道我只需要使用if(price.equals("sale") == true)
。但是,如果我希望用户键入单词中带有空格的内容,就会出现问题,例如:if(price.equals("regular price") == true)
,当用户键入“正常价格”时,我没有得到想要的响应。
我也在顺便学习Java。
答案 0 :(得分:2)
您可以确定字符串是否包含这样的单词:
if (price.toLowerCase().contains("regular"))
如果想花哨的话,可以使用正则表达式来匹配整个单词(例如,不是“ irregular”):
if (price.matches("(?i).*\\bregular\\b.*"))
答案 1 :(得分:0)
您要比较带空格的字符串吗? 然后您可以先比较它们的长度,然后
如果字符串包含space
,则将其分割,再次比较长度,然后检查每个字符串。
如果其中不包含空格,只需使用一次equals
,这就是我想出的内容:
class cmp {
public static void main(String[] args) {
String s = "test some";
String s2 = "test some";
String s3 = "test not";
String s4 = "testxsome";
System.out.println(cmpStr(s,s2)); // True
System.out.println(cmpStr(s,s3)); // False
System.out.println(cmpStr(s,s4)); // False
}
public static boolean cmpStr(String str1, String str2) {
if (str1.length() != str2.length()) {
System.out.println("Length mismatch.");
return false;
}
if (str1.contains(" ") || str2.contains(" ")) {
String[] a1 = str1.split(" ");
String[] a2 = str2.split(" ");
if (a1.length != a2.length) {
System.out.println("Split Length mismatch.");
return false;
}
for (int i = 0; i < a1.length; i++) {
if (!a1[i].equals(a2[i])) {
System.out.println("One of split mismatch." + a1[i] + " " + a2[i] );
return false;
}
}
} else {
if (!str1.equals(str2)) {
System.out.println("Regular equals returns false.");
return false;
}
}
return true;
}
}
答案 2 :(得分:0)
我在这里看到三种方法
从字符串中删除所有空格和隐藏字符并检查
String input = "regular price";
input = input.replaceAll("\\s+","");
if(price.equals(input))
{
//your code here
}
检查单词是否包含关键字
if (price.toLowerCase().contains("regular"))
创建一个正则表达式以匹配您的单词
答案 3 :(得分:0)
java equals()方法/函数也可以完美地与空格配合使用。另外,您不需要将结果与true / false进行比较。如果两个字符串相等,则equals()将自动返回true,否则将返回false。
public class MyClass {
public static void main(String args[]) {
String a = "A B C";
if(a.equals("A B C")){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
我测试了以下程序,当字符串中包含空格时,它返回true。