Java - 为什么我不能使用 charAt() 来查看一个字符是否等于另一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26688990/
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-08-11 03:04:05  来源:igfitidea点击:

Java - Why can't I use charAt() to see if a char equals another?

javastringcharequals

提问by Mayron

I want to see if a character in my string equals a certain other char value but I do not know what the char in the string is so I have used this:

我想看看我的字符串中的一个字符是否等于某个其他字符值,但我不知道字符串中的字符是什么,所以我使用了这个:

if ( fieldNames.charAt(4) == "f" )

But I get the error:

但我收到错误:

"Operator '==' cannot be applied to 'char', 'jav.lang.String'"

But "g" == "h"seems to work and I know you can use '=='with char types.

"g" == "h"似乎有效,我知道您可以使用'=='char 类型。

Is there another way to do this correctly? Thanks!

有没有另一种方法可以正确地做到这一点?谢谢!

采纳答案by Madhawa Priyashantha

if ( fieldNames.charAt(4) == 'f' )

because "f"is a Stringand fieldNames.charAt(4)is a char. you should use 'f'for check char

因为"f"是一个String并且fieldNames.charAt(4)是一个char。你应该'f'用于检查字符

"g" == "h"works because both g and h are Strings

"g" == "h"有效,因为 g 和 h 都是 Strings

and you shouldn't use "g" == "h"you should use "g".equals("h")instead . you can use == for primitivedata types like char,int,boolean....etc.but for the objectslike String it's really different. To know why read this

你不应该使用 "g" == "h"你应该使用"g".equals("h")。您可以将 == 用于primitive诸如char,int,boolean....etc 之objects类的数据类型,但对于诸如 String 之类的数据类型,它确实不同。 要知道为什么读这个

but you can use also

但你也可以使用

'g' == 'h' 

you should wrap Strings by double quotation and char by single quotation

你应该用双引号包裹字符串,用单引号包裹字符

String s="g";

char c='g';

but char can only have one character but String can have more than one

但 char 只能有一个字符,而 String 可以有多个

String s="gg";  valid

char c='gg';  not valid

回答by And

I was having the same problem, but I was able to solve it using:

我遇到了同样的问题,但我能够使用以下方法解决它:

if (str.substring(0,1).equals("x") )

the substring can be used in a loop str.substring(i, i + 1)

子字符串可以在循环中使用 str.substring(i, i + 1)

charAt(i).equals('x') will not work together

charAt(i).equals('x') 不能一起工作

回答by J?rgen Bauer

This works:

这有效:

if (String(fieldNames.charAt(4)) == "f")

if (String(fieldNames.charAt(4)) == "f")