我有一串国家缩写的注释,我想将它们分开,以便我可以识别每个缩写的国家.这样我将拥有String c = USA; 我将输出国家名称......
目前它没有c = USA但只有A
public class Example {
public static void main(String[] args) {
String x = "USAIND";
String c = "";
System.out.print("Country: ");
for (int i = 0; i < 3; i++) {
c = Character.toString(x.charAt(i));
System.out.print(c);
if (c.equals("USA")) {
System.out.println("United State of America");
}
}
System.out.println("");
System.out.print("Country: ");
for (int i = 3; i < 6; i++) {
c = Character.toString(x.charAt(i));
System.out.print(c);
if (c.equals("IND")) {
System.out.println("India");
}
}
System.out.println("");
}
}
Run Code Online (Sandbox Code Playgroud)
你需要将每个字符附加到你的字符串然后比较它,否则,它将始终用最后一个字符替换你的字符串.
for (int i = 0; i < 3; i++) {
c += Character.toString(x.charAt(i)); // Appending all the characters one by one
}
System.out.print(c); // Printing the String c after all the characters are appending
if (c.equals("USA")) { // checking if its equal to USA
System.out.println("United State of America");
}
Run Code Online (Sandbox Code Playgroud)
这个过程的另一半也是如此.
c = ""; // re-initialize it to blank
for (int i = 3; i < 6; i++) {
c += Character.toString(x.charAt(i));
}
System.out.print(c);
if (c.equals("IND")) {
System.out.println("India");
}
Run Code Online (Sandbox Code Playgroud)
但最简单的方法是使用String.substring(startIndex, endIndex)它.
String c = x.substring(0,3); // For USA
String c1 = x.substring(3,6); // For IND
Run Code Online (Sandbox Code Playgroud)