[英]how to use replace function in java for case insensitive character value
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. 我正在编写一个Java程序,其中用户输入一系列单词,该单词将句子中的每个“ p”更改为“ b”(不区分大小写)并显示输出。
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
. 我期望产出的boliticians bromised
,但是实际产出是Politicians bromised
。
replace
is case sensitive only. replace
仅区分大小写。
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.