[英]Java: Replace a specific character with a substring in a string at index
I am struggling with how to actually do this. 我正在努力如何实际做到这一点。 Say I have this string
说我有这个字符串
"This Str1ng i5 fun" “这Str1ng i5的乐趣”
I want to replace the '1' with "One" and the 5 with "Five" 我想将“ 1”替换为“一个”,将5替换为“五个”
"This StrOneng iFive fun" “这StrOneng iFive乐趣”
I have tried to loop thorough the string and manually replace them, but the count is off. 我尝试循环遍历字符串并手动替换它们,但是计数已关闭。 I have also tried to use lists, arrays, stringbuilder, etc. but I cannot get it to work:
我也尝试过使用列表,数组,stringbuilder等,但无法正常工作:
char[] stringAsCharArray = inputString.toCharArray();
ArrayList<Character> charArraylist = new ArrayList<Character>();
for(char character: stringAsCharArray) {
charArraylist.add(character);
}
int counter = startPosition;
while(counter < endPosition) {
char temp = charArraylist.get(counter);
String tempString = Character.toString(temp);
if(Character.isDigit(temp)){
char[] tempChars = digits.getDigitString(Integer.parseInt(tempString)).toCharArray(); //convert to number
charArraylist.remove(counter);
int addCounter = counter;
for(char character: tempChars) {
charArraylist.add(addCounter, character);
addCounter++;
}
counter += tempChars.length;
endPosition += tempChars.length;
}
counter++;
}
I feel like there has to be a simple way to replace a single character at a string with a substring, without having to do all this iterating. 我觉得必须有一种简单的方法来用子字符串替换字符串中的单个字符,而不必进行所有这些迭代。 Am I wrong here?
我在这里错了吗?
You can do 你可以做
string = string.replace("1", "one");
Don't use replaceAll
, because that replaces based on regular expression matches (so that you have to be careful about special characters in the pattern, not a problem here). 不要使用
replaceAll
,因为它是根据正则表达式匹配进行替换的(因此您必须注意模式中的特殊字符,这里不是问题)。
Despite the name, replace
also replaces all occurrences. 尽管名称如此,
replace
也会替换所有出现的事件。
Since Strings are immutable, be sure to assign the result value somewhere. 由于字符串是不可变的,因此请确保将结果值分配在某个位置。
String[][] arr = {{"1", "one"},
{"5", "five"}};
String str = "String5";
for(String[] a: arr) {
str = str.replace(a[0], a[1]);
}
System.out.println(str);
This would help you to replace multiple words with different text. 这将帮助您用不同的文本替换多个单词。
Alternatively you could use chained replace for doing this, eg : 或者,您可以使用链接替换来执行此操作,例如:
str.replace(1, "One").replace(5, "five");
Check this much better approach : Java Replacing multiple different substring in a string at once (or in the most efficient way) 检查这种更好的方法: Java一次(或以最有效的方式)替换字符串中的多个不同子字符串
Try the below: 请尝试以下方法:
string = string.replace("1", "one");
string = string.replace("5", "five");
.replace
replaces all occurences of the given string with the specified string, and is quite useful. .replace
用指定的字符串替换所有出现的给定字符串,并且非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.