如果您正在比较两个字符串(即数组是String[]
),那么您的代码正在比较每个字符串的内存引用,这将是不同的。
为了比较String
是否相等,您需要使用该equals
方法。
for(x = 0; x < fullName.length(); x++)
{
if(fullName[0].equals(nameUpperCase[2]));
{
System.out.print("character [0] located at position [0] is lowercase");
}
if(fullName[1].equals(nameLowerCase[4]));
{
System.out.print("character [b] located at position [1] is uppercase");
}
}
我还建议您从其他答案中汲取一些想法。
将原始转换String
为 char 数组而不是...
char[] fullName = name.toCharArray();
或者您可以简单地获取给定索引处的字符...
for(x = 0; x < originalString.length(); x++)
{
char charAt = originalString.charAt(x);
if(Character.isUpperCase(charAt));
{
System.out.print("character [0] located at position [0] is lowercase");
}
if(Character.toUpperCase(originalString.charAt(1)) == originalString.charAt(4));
{
System.out.print("character [b] located at position [1] is uppercase");
}
}
更新示例
既然我们已经确定我们无法将String
值与进行比较==
,这里有一个我认为你想要实现的工作示例......
String value = "This is a simple string";
for (int index = 0; index < value.length(); index++) {
String whatIs = "Unknown";
if (Character.isUpperCase(value.charAt(index))) {
whatIs = "Upper case";
} else if (Character.isLowerCase(value.charAt(index))) {
whatIs = "Lower case";
} else if (Character.isSpaceChar(value.charAt(index))) {
whatIs = "Space";
} else if (Character.isDigit(value.charAt(index))) {
whatIs = "Digit";
}
System.out.println("Character @ " + index + " (" + value.charAt(index) + ") is a " + whatIs + " character");
}
哪个输出
Character @ 0 (T) is a Upper case character
Character @ 1 (h) is a Lower case character
Character @ 2 (i) is a Lower case character
Character @ 3 (s) is a Lower case character
Character @ 4 ( ) is a Space character
Character @ 5 (i) is a Lower case character
Character @ 6 (s) is a Lower case character
Character @ 7 ( ) is a Space character
Character @ 8 (a) is a Lower case character
Character @ 9 ( ) is a Space character
Character @ 10 (s) is a Lower case character
Character @ 11 (i) is a Lower case character
Character @ 12 (m) is a Lower case character
Character @ 13 (p) is a Lower case character
Character @ 14 (l) is a Lower case character
Character @ 15 (e) is a Lower case character
Character @ 16 ( ) is a Space character
Character @ 17 (s) is a Lower case character
Character @ 18 (t) is a Lower case character
Character @ 19 (r) is a Lower case character
Character @ 20 (i) is a Lower case character
Character @ 21 (n) is a Lower case character
Character @ 22 (g) is a Lower case character