用数字替换 char 数组中的 char 时出现问题
Problem replacing char in char array with a digit
给定一个字符串,我必须用它们在数组中的相应位置替换所有元音。但是,我的代码 returns 一些奇怪的符号而不是数字。问题出在哪里?
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;
和
char y = '1'
不持有相同的值,这是因为许多数字表示与 ascii 代码相关,并且您必须分配给 y 以打印数字 1 的值是 HEX 0x31 或 DEC 49。
看看ascci table
给定一个字符串,我必须用它们在数组中的相应位置替换所有元音。但是,我的代码 returns 一些奇怪的符号而不是数字。问题出在哪里?
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; 和 char y = '1'
不持有相同的值,这是因为许多数字表示与 ascii 代码相关,并且您必须分配给 y 以打印数字 1 的值是 HEX 0x31 或 DEC 49。
看看ascci table