简体   繁体   English

如何检查一个字符串中是否至少有一个字符组成数组? (JAVA)

[英]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.

相关问题 java中如何判断一个字符串是否至少包含一个字母? - How to check whether a string contains at least one alphabet in java? 正则表达式模式如何写入以检查 Java 中的至少一个字符串和数字? - How regex pattern write to check at least one string and number in Java? 如何用Java对角检查2D Char数组中的字符串(Eclipse) - How to Diagonally Check String in a 2D Char Array in Java (Eclipse) 有没有办法用java递归检查字符串是否包含至少一个大写字母? - Is there a way to check if a string contains at least one capital letter recursively with java? 如何使用正则表达式检查Java中的字符串是否以至少一位数字结尾? - How do you use regular expressions to check if a String in Java ends with at least one digit? 如何检查 Java 字符串是否至少包含一个大写字母、小写字母和数字? - How do I check if a Java String contains at least one capital letter, lowercase letter, and number? 如何通过在Java中通过char添加char从char数组创建字符串 - how to create a string from char array by adding char by char in java 如何检查Set B是否至少有一个元素不在Set A中 - How to check if Set B has at least one element that is not in Set A 如何检查列表是否至少包含一个元素而不循环 - How to check if list has at least one element without looping 如何检查字符串是否包含 Java 中数组的任何元素? - how to check if a string contains any element of an array in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM