I am writing a java program in which a user enters a series of words that changes every 'p' to a 'b' in the sentence (case insensitive) and displays the output.
I try to use replace function but it is not case insensitive
String result = s.replace('p', 'b');
I expect the output boliticians bromised
, but the actual outputs is Politicians bromised
.
replace
is case sensitive only.
There is no "simple" way to do this: you could do two replacements, but that constructs an intermediate string.
String result = s.replace('p', 'b').replace('P', 'B');
I would do this by iterating the character array:
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; ++i) {
switch (cs[i]) {
case 'p': cs[i] = 'b'; break;
case 'P': cs[i] = 'B'; break;
}
}
String result = new String(cs);
If you wanted to write a method to do this for non-hardcoded letters, you could do it like:
String method(String s, char from, char to) {
char ucFrom = Character.toUpperCase(from); // Careful with locale.
char ucTo = Character.toUpperCase(to);
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; ++i) {
if (cs[i] == from) { cs[i] = to; }
else if (cs[i] == ucFrom) { cs[i] = ucTo; }
}
return new String(cs);
}
您可以使用正则表达式进行操作,请参阅问答- 如何在Java中替换不区分大小写的文字子字符串,也可以对p和P两次使用replace
您可以改用replaceAll
以便使用正则表达式:
String result = s.replaceAll("[pP]", "b");
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.