[英]How do I replace one character occurrence in a string?
How would I replace a string like "Hello" with "Helko", only replacing the second L but not the first?如何用“Helko”替换像“Hello”这样的字符串,只替换第二个 L 而不是第一个?
Use replaceAll with regular expression:将 replaceAll 与正则表达式一起使用:
System.out.println("Hello".replaceAll("((?!^).*?|[^l]*l.*?)l","$1k"));
Simple Approach (based on excluding the second l
) :简单方法(基于排除第二个l
) :
l
using indexOf
and do another search for l
but this time start searching from firstL
+ 1 which will lead to the second index l
if exist!使用indexOf
搜索l
的第一个索引并再次搜索l
但这次从firstL
+ 1开始搜索,这将导致第二个索引l
如果存在!l
, If So Exclude the second l
by using substring
which take only the first part (start from zero till secondL
) and second part (start from secondL
+1 till the end) , Concatenate them with k
.如果有第二个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;
}
Tests:测试:
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
}
Another Approach: Convert the String into a char array, and declare a variable lFound
gonna look for the first occurrence of letter l
, if it found next l
will be converted to k
and exit the loop by break
.另一种方法:将 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
Lately , I turned to the conversation and I saw you writing:最近,我转向谈话,我看到你在写:
I wanted to replace one instance of a character with another, like "aaaaa" with "aabaa", where only the third 'a' is replaced with 'b', but not the others.我想将一个字符的一个实例替换为另一个,例如将“aaaaa”替换为“aabaa”,其中只有第三个“a”被替换为“b”,而不是其他的。
Just follow second approach I posted with additional tests.只需按照我发布的第二种方法进行附加测试即可。
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;
}
Test:测试:
String str = "aaaaa";
System.out.println(removeSpecificChar(str, 'a', 'b', 3));
Print:打印:
aabaa
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.