-3

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?

Marcelo Melo
  • 107
  • 3
  • 10
  • 2
    How do we check if it exists? Do we assume that you can do that? – Spectric Sep 28 '20 at 14:08
  • SideNote: Make sure it is easy to replace such a validator for zip codes later. If you discover one day that you wish to process adresses from other countries, you will need different rules. – Hulk Sep 28 '20 at 14:11
  • 2
    Please share your attempt to implement replacement – Slava Medvediev Sep 28 '20 at 14:11
  • 1
    @MarceloMelo, you should use a char array of the initial string or put this string into StringBuilder and then you'll be able to modify the contents of the array/StringBuilder. To print each attempt you need to create a new String instance of that array/StringBuilder. – Nowhere Man Oct 04 '20 at 10:53

1 Answers1

1

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

CLAIN Cyril
  • 123
  • 9