[英]How can I check if a character in a string is equal to any position in an array?
我正在尝试比较字符串的第一个字符,以确保它不等于数组中的任何位置。 这是代码:
if(string.charAt(0) != array[0] || string.charAt(0) != array[1])
{
//Code here
}
我在实际代码中检查了10个位置的数组,但这实在太多了。 有没有更简单的方法可以做到这一点? 如果是这样,怎么办?
使用for loop
for(int i = 0; i < array.length; i++){
if(string.charAt(0) != array[i])
{
//Code here
break;
}
}
甚至是while loop
int i = 0;
while(i < array.length){
if(string.charAt(0) != array[i])
{
//Code here
break;
}
}
为什么该死的不允许螺丝迭代并进行一些递归。 (假设数组的类型为char)。 其他方法更好,我只是想证明您可以使用递归来做到这一点。
boolean checkChar(String string Char[] array){
return checkCharHelper(string, array, 0);
}
boolean checkCharHelper(String string, Char[] array, int index){
if(index >= string.length){
return false;
}
if(string.charAt(0) != array[i])
{
//Code here
return true;
}
return checkCharHelper(string, array, index + 1);
}
Java 8 powa
int[] array = {'a','b','c'};
String s1 = "cat";
String s2 = "dog";
boolean res1 = Arrays.stream(array).anyMatch(c -> c==s1.charAt(0));
boolean res2 = Arrays.stream(array).anyMatch(c -> c==s2.charAt(0));
System.out.println(res1); //true
System.out.println(res2); //false
for (char c : array) {
if (string.charAt(0) != c) {
// Code here
break;
}
}
遍历数组并检查每个位置。 如果找到一个匹配的标志,请设置一个标志。
boolean flag = false;
for (int i = 0; i < array.length; i++) {
if (string.charAt(0) == array[i]) {
flag = true;
break;
}
}
if (flag) {
// Indicates that one of them was equal.
} else {
// None of them was equal.
}
使用List
而不是静态数组,然后也使用List#contains()
方法。
样例代码:
List<Character> list = Arrays.asList('a', 'b', 'c');
if (!list.contains(string.charAt(0))) {
System.out.println("not found in array");
}
创建一个单独的方法来遍历数组,并将数组中的每个字符与给定字符(在本例中为字符串的第一个字符)进行比较。
private boolean charInArray(char[] chars, char c){
for(char x: chars)
if(c == x) return true;
return false;
}
您可以这样称呼它:
if(!charInArray(array, string.charAt(0)){
//do something
}
我认为for循环是最好的选择。 遍历数组,检查每个索引以查找字符串开头的字符。
//Your string
String yourString = "some string";
boolean interrupt = false;
for (int i = 0; i < array.length; i++) {
if(yourString.charAt(0).equalsIgnoreCase(array[i])) {
interrupt = true;
break;
}
}
if(interrupt) {
System.out.println("Found in array");
}
else {
System.out.println("Not found in array");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.