将 ascii 值转换为字符串中的对应字符 (Ex - T104a110k115) - java
Converting ascii value to correspondence char in a string (Ex - T104a110k115) - java
我已经将 char 的偶数位置转换为 ascii 值,我希望这些 ascii 值再次转换回 char。
所以字符串值为“Thanks”
转换后的值为“T104a110k115”
我想要它再次“谢谢”。
我用过的程序...转换
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Str2.length(); i++) {
if (i % 2 != 0) {
int m = Str2.charAt(i);
sb.append(m); // add the ascii value to the string
} else {
sb.append(Str2.charAt(i)); // add the normal character
}
}
System.out.println("Replaced even chart with ascii--"+sb.toString());
sb.append(3);
System.out.println("added a int--"+sb.toString());
注:本回答使用正则表达式。如果您不知道正则表达式,现在可能是上网学习的好时机。
在Java11及之后的版本中,您可以这样操作:
String input = "T104a110k115";
String result = Pattern.compile("\d+").matcher(input)
.replaceAll(r -> Character.toString(Integer.parseInt(r.group())));
System.out.println(result); // prints: Thanks
在旧版本(Java 1.4 及更高版本)中,您可以这样做:
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("\d+").matcher(input);
while (m.find()) {
char c = (char) Integer.parseInt(m.group());
m.appendReplacement(buf, String.valueOf(c));
}
String result = m.appendTail(buf).toString();
我已经将 char 的偶数位置转换为 ascii 值,我希望这些 ascii 值再次转换回 char。
所以字符串值为“Thanks”
转换后的值为“T104a110k115”
我想要它再次“谢谢”。
我用过的程序...转换
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Str2.length(); i++) {
if (i % 2 != 0) {
int m = Str2.charAt(i);
sb.append(m); // add the ascii value to the string
} else {
sb.append(Str2.charAt(i)); // add the normal character
}
}
System.out.println("Replaced even chart with ascii--"+sb.toString());
sb.append(3);
System.out.println("added a int--"+sb.toString());
注:本回答使用正则表达式。如果您不知道正则表达式,现在可能是上网学习的好时机。
在Java11及之后的版本中,您可以这样操作:
String input = "T104a110k115";
String result = Pattern.compile("\d+").matcher(input)
.replaceAll(r -> Character.toString(Integer.parseInt(r.group())));
System.out.println(result); // prints: Thanks
在旧版本(Java 1.4 及更高版本)中,您可以这样做:
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("\d+").matcher(input);
while (m.find()) {
char c = (char) Integer.parseInt(m.group());
m.appendReplacement(buf, String.valueOf(c));
}
String result = m.appendTail(buf).toString();