[英]How to check if at least one element form a char array is in a String? (Java)
For example you have the String 'Hello World' and you want to check if at least one element of a char array is in the String. 例如,您有一个字符串“ Hello World”,并且您要检查字符串中是否至少有一个char数组元素。 This is what my code looks like but it doesnt work somehow... :-/
这是我的代码的样子,但是无法正常工作...:-/
public boolean check(String toCheck){
int n = toCheck.length();
int true_counter = 0;
for(int i = 0; i < n; i++){
if(toCheck.indexOf(charArray[i]) != -1){
true_counter++;;
}
}
if(true_counter > 0)
return true;
else
return false;
}
the char array is part of the class. char数组是该类的一部分。 Can someone help me?
有人能帮我吗?
You need to run your loop up to the length of charArray
, not up to the length of the String
: 您需要将循环运行到
charArray
的长度,而不是String
的长度:
int n = charArray.length();
Moreover, you could stop as soon as you find the character, without counting the number of matches: 而且,您可以在找到字符后立即停止,而无需计算匹配数:
for(int i = 0; i < n; i++){
if(toCheck.indexOf(charArray[i]) != -1){
return true;
}
}
return false;
If you reach the end of the loop without finding a match, you would get to the return false
statement. 如果到达循环末尾而没有找到匹配项,则将
return false
语句。
You could loop over the char array and return as soon as you find a character in the string. 您可以遍历char数组,并在字符串中找到一个字符后立即返回。
for (char character : charArray){
if (checkString.indexOf(character) != -1){
return true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.