[英]How do you check to compare a string value to each element in an array?
So I have a String Array (sConsonantArray) and have all of the consonants stored in it. 所以我有一个字符串数组(sConsonantArray)并且存储了所有辅音。
String[] sConsonantArray = new String[] {"q","w","r","t","p","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"};
I need to check if the second last value of a word (sWord) equals a value in the array and I don't know how to call each value in the array to compare the letters other than doing sConsonantArray[5] (checking them each one at a time). 我需要检查一个单词的第二个最后一个值(sWord)是否等于数组中的值,我不知道如何调用数组中的每个值来比较除了执行sConsonantArray之外的字母[5](每个都检查它们)一次一个)。 I am looking for an easier way to call them, thanks for your help.
我正在寻找一种更简单的方式来打电话给他们,感谢您的帮助。 Also, it doesn't appear that the (&&) operator will work, other suggestions would be appreciated.
此外,似乎(&&)运算符不起作用,其他建议将不胜感激。
else if (sWord.substring(sWord.length()-2,sWord.length()-1).equals(sConsonantArray I DONT KNOW WHAT TO PUT HERE)) && (sWord.substring(sWord.length()-1,sWord.length()).equalsIgnoreCase("o"))
{
System.out.println("The plural of " + sWord + " is " + (sWord + "es"));
}
It seems to me that it would be simpler to have the consonants as a string and then use charAt
: 在我看来,将辅音作为字符串然后使用
charAt
会更简单:
private static final String CONSONANTS = "bcdfgh...z";
if (CONSONANTS.indexOf(word.charAt(word.length() - 2)) {
...
}
If you really want to use an array, you could change your array to be in order and then call Arrays.binarySearch
. 如果您确实想要使用数组,可以将数组更改为有序,然后调用
Arrays.binarySearch
。 Another alternative would be to create a HashSet<String>
of the consonants and use contains
on that. 另一种方法是创建辅音的
HashSet<String>
并在其上使用contains
。
Try something like 尝试类似的东西
else if (Arrays.asList(sConsonantArray).contains(
sWord.substring(sWord.length()-2,sWord.length()-1))
&& (sWord.substring(sWord.length()-1,sWord.length()).equalsIgnoreCase("o"))) {
// do something
}
or Write a small Util method 或者写一个小的Util方法
public static boolean isInConstants(String yourString){
String[] sConsonantArray = new String[] {"q","w...}
for (String item : sConsonantArray) {
if (yourString.equalsIgnoreCase(item)) {
return true;
}
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.