英文:
How do I replace characters of a string, from right to left, cumulatively?
问题
public class StringReplacer {
public static void main(String[] args) {
String test = "12345678";
StringReplacer replacer = new StringReplacer();
for (int i = test.length() - 1; i >= 0; i--) {
test = replacer.replaceFromRightToLeft(test, i);
System.out.println(test);
}
}
public String replaceFromRightToLeft(String input, int index) {
StringBuilder builder = new StringBuilder(input);
for (int i = input.length() - 1; i > index; i--) {
builder.setCharAt(i, '0');
}
return builder.toString();
}
}
英文:
I'm trying to write a function that receives a String, and replaces the string characters from right to left, by zero. Also, I'd like to make it accumulate and save those changes. For example:
String test = "12345678"
When I iterate through it, I'd like the result to be:
- "12345670"
- "12345600"
- "12345000"
- "12340000"... and so on.
Here's the code I've written so far:
public String test = "12345678";
public String replaceFromRightToLeft(String test) {
for (int i = test.length() -1; i >= 0; i--) {
test.replace(test.charAt(i), '0');
}
return test;
}
When I run it, I get results like:
- 12345670
- 12345608
- 12345078
- 12340678
- 12305678
- 12045678
- 10345678
- 02345678
So, what should I do to "save" the previous changes?
答案1
得分: 1
字符串是不可变的,因此创建一个新的字符串
String result = zip.substring(0, length - 2) + yourNewChar;
编辑:我在注释中看到了replace()
,它比我写的更好。
英文:
String are immutable so make a new string
String result = zip.substring(0,length-2) + yourNewChar
edit : i see in the comment replace()
and it's better than what i write
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论