我试图将字符串"ABCD"
拆分为一个数组,该数组将保存值["AB","BC","CD"]
,但我不确定如何处理。
Here's an idea:
String string1 = "ABCD";
for(int i = 0; i < string1.length() - 1; i++){
String string2 = Character.toString(string1.charAt(i));
string2 += Character.toString(string1.charAt(i+1));
System.out.println(string2);
}
What "Character.toString(string1.charAt(i))" does is basically find the character of string1's "i" value. So for example, if i = 0, string2 would equal string1's value at 0, which is "A". Then, in the next line of code, string2 adds string1's value of "i+1" (which is the next letter, so B). Therefore, it will print "AB", "BC, and "CD".
Can be done really easily:
String string = "ABCDEFGH";
String[] result = new String[string.length() - 1];
for(int i = 0; i < result.length; i++) {
result[i] = string.charAt(i) + "" + string.charAt(i+1);
}
Variable "result" consists of:
"AB"
"BC"
"CD"
"DE"
"EF"
"FG"
"GH"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.