[英]How do I replace one character occurrence in a string?
如何用“Helko”替换像“Hello”这样的字符串,只替换第二个 L 而不是第一个?
将 replaceAll 与正则表达式一起使用:
System.out.println("Hello".replaceAll("((?!^).*?|[^l]*l.*?)l","$1k"));
简单方法(基于排除第二个l
) :
indexOf
搜索l
的第一个索引并再次搜索l
但这次从firstL
+ 1开始搜索,这将导致第二个索引l
如果存在!l
进行测试,如果有,则使用substring
排除第二个l
,它只占用第一部分(从零开始到secondL
)和第二部分(从secondL
+1 到结束) ,将它们与k
连接。public static String removeSecondL(String str) {
int firstL = str.indexOf('l');
int secondL = str.indexOf('l', firstL+1);
if(secondL != -1) {
String firstPart = str.substring(0, secondL);
String secondPart = str.substring(secondL + 1);
return firstPart + 'k' + secondPart;
}
return str;
}
测试:
public static void main(String[] args) {
System.out.println(removeSecondL("Hello")); // Helko
System.out.println(removeSecondL("lololo")); // lokolo
System.out.println(removeSecondL("no l")); // no l
}
另一种方法:将 String 转换为 char 数组,并声明一个变量lFound
将查找第一次出现的字母l
,如果找到下一个l
将转换为k
并通过break
退出循环。
String str = "Hello";
char[] chars = str.toCharArray();
boolean lFound = false;
for (int i = 0; i < chars.length; i++) {
if(lFound) {
if(chars[i] == 'l')
{
chars[i] = 'K';
break;
}
}else {
lFound = chars[i] == 'l'; //if(chars[i] == 'l') lFound = true;
}
}
System.out.println(chars); //HelKo
最近,我转向谈话,我看到你在写:
我想将一个字符的一个实例替换为另一个,例如将“aaaaa”替换为“aabaa”,其中只有第三个“a”被替换为“b”,而不是其他的。
只需按照我发布的第二种方法进行附加测试即可。
public static char[] removeSpecificChar(String str, char a, char b, int position) {
char[] chars = str.toCharArray();
int pos = 1;
for (int i = 0; i < chars.length; i++) {
if(pos == position) {
if(chars[i] == a)
{
chars[i] = b;
break;
}
}else {
pos += (chars[i] == a) ? 1 : 0;
}
}
return chars;
}
测试:
String str = "aaaaa";
System.out.println(removeSpecificChar(str, 'a', 'b', 3));
打印:
aabaa
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.