问题描述
给定一个字符串,我必须用它们在数组中的各自位置替换所有元音。但是,我的代码返回一些奇怪的符号而不是数字。问题出在哪里?
String s = "this is my string";
char p = 1;
char[] formatted = s.tochararray();
for(int i = 0; i < formatted.length; i++) {
if(formatted[i] == 'a' ||formatted[i] == 'e' ||formatted[i] == 'i'
||formatted[i] == 'o' ||formatted[i] == 'u') {
formatted[i] = p;
}
p++;
}
s = String.valueOf(formatted);
System.out.println(s);
P.S:数字大于 10
解决方法
字符 '1'
与数字 1
的值不同。
你可以改变
char p = 1;
到
char p = '1';
我认为这会给你你想要的,只要你不试图在你的字符串中插入超过 9 个数字。否则,您将需要处理插入额外的数字,而您无法将其插入到字符数组中,因为它具有固定长度。
,this is my s t r i n g
012345678910 11 12 13 14
i
中string
的位置是14
但14
不是字符;它是一个数字字符串。这意味着您需要处理字符串而不是字符。使用 s
作为分隔符拆分 ""
,处理结果数组,最后使用 ""
作为分隔符将数组连接回字符串。
class Main {
public static void main(String[] args) {
String s = "this is my string";
String[] formatted = s.split("");
for (int i = 0; i < formatted.length; i++) {
if (formatted[i].matches("(?i)[aeiou]")) {
formatted[i] = String.valueOf(i);
}
}
s = String.join("",formatted);
System.out.println(s);
}
}
输出:
th2s 5s my str14ng
正则表达式 (?i)[aeiou]
为其中一个元音指定不区分大小写的匹配,其中 (?i)
指定不区分大小写。 Test it here。
问题的根源已经在评论中了,
在 java 中,类型在内存大小及其表示上有所不同
int x = 1; 和 字符 y = '1'
没有保持相同的值,这是因为许多数字表示与 ascii 代码相关,并且您必须分配给 y 才能打印数字 1 的值是 HEX 0x31 或 DEC 49。
看看ascci表