[英]Creating a string character by character in Java
所以我創建了這個程序:
class Input {
public static void main(String[] args) throws Exception {
String hexa;
hexa = "";
int pituus;
pituus = hexa.length();
int i = 1;
char luku;
char luku2;
while (i < pituus) {
luku = hexa.charAt(i);
luku2 = hexa.charAt(i - 1);
luku++;
if (luku == 'G') {
luku = '0';
luku2++;
} else if (luku == ':')
luku = 'A';
if (luku2 == '8')
luku2 = '0';
System.out.print(luku2);
System.out.print(luku);
i += 2;
}
System.out.println();
}
}
如您所知,它會打印原始的十六進制字符串,但會在每對字符上加1,我希望這兩對字符的最大值為7F。 但是,該程序才剛剛開始,為了進一步進行,我需要一個帶有所有字符打印的字符串。 那可能嗎?
要動態創建字符串,可以使用StringBuilder。 只需在其上附加字符即可
StringBuilder sb = new StringBuilder();// builder is empty now
// some logic
for (char ch = 'a'; ch <= 'z'; ch++) {
// for this example we will just add all lower-case
// characters to builder
sb.append(ch);
}
// after all characres are placed in builder
// lets convert it to string
String alphabet = sb.toString();
// and see what we got
System.out.println(alphabet);
輸出:動態生成的字母
abcdefghijklmnopqrstuvwxyz
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.