JAVA - 字符串包含字符字母。可以检查吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31950361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:24:09  来源:igfitidea点击:

JAVA - String contains char letter. Possible to check?

javastringcharcontains

提问by Thrillofit123

I am trying to make a method called Baller(String str, char chr)which should return a boolean if the word contains the character. In the main method I have:

我正在尝试创建一个调用的方法Baller(String str, char chr),如果单词包含该字符,它应该返回一个布尔值。在主要方法中,我有:

public static void main(String[] args) {
    Balling ball= new Balling ();
    System.out.println( ball.contains("Baller", 'a'));
    System.out.println( ball.contains("Baller", 'A'));
}

What I did was this but it did not work:

我所做的是这样,但它不起作用:

public boolean contains(String str, char chr ) {
    if(str.length() == chr) {
        return true;
    }
    else {
        return false;
    }       
}

What could be the problem?

可能是什么问题呢?

ANSWER

回答

public boolean contains(String str, char chr ) {

        for(int i = 0; i < str.length(); i++)
            if(str.charAt(i) == chr)
                return true;
        return false;
    }
}

回答by MaxZoom

The problem is that string length is compared to character value:

问题是将字符串长度与字符值进行比较:

str.length() == chr

What you should use if the indexOfString method

如果indexOfString 方法应该使用什么

public boolean contains(String str, char chr) {
  return str.indexOf(chr) != -1;
}

回答by Florian Schaetz

You are testing if the length of the String is equal to some char. This will perhaps work if your String is of length zero and your character == 0 or perhaps if your String is of length one and you compare it to the character with the numeric value of 1. In other words: Almost never.

您正在测试字符串的长度是否等于某个字符。如果您的字符串长度为零并且您的字符 == 0,或者您的字符串长度为 1 并且您将其与数值为 1 的字符进行比较,这可能会起作用。换句话说:几乎从不。

You never return false. So all your string contain all your characters.

你永远不会返回假。所以你所有的字符串都包含你所有的字符。

String has an indexOf( character )method. use that. See documentation.

字符串有一个indexOf( character )方法。用那个。请参阅文档