如何将字符串中的字符从右到左累积地进行替换?

huangapple go评论118阅读模式
英文:

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:

  1. "12345670"
  2. "12345600"
  3. "12345000"
  4. "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:

  1. 12345670
  2. 12345608
  3. 12345078
  4. 12340678
  5. 12305678
  6. 12045678
  7. 10345678
  8. 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

huangapple
  • 本文由 发表于 2020年9月28日 22:04:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64103767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定