Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting a variable to zero while in a loop

Tags:

java

I have this code that allows me to take a string and replace all the vowels with an increasing number.

For example, "abababababababababababa" would give me "0b1b2b3b4b5b6b7b8b9b10b11". I am trying to keep it so that the number, once it goes past 9, resets to zero and starts counting back up again (so that "0b1b2b3b4b5b6b7b8b9b10b11" would instead read "0b1b2b3b4b5b6b7b8b9b0b1").

I can't figure out a way to do it within the loop that isn't fairly convoluted. If there is some way of achieving this that someone wouldn't mind divulging, that would be greatly appreciated.

public static String getNumberString( String s)
{
 String word = s;
 String word1 = word.replaceAll("[AEIOUaeiou]", "@");
 int c = 0;

 String word2 =  word1;
 for( c = 0; c <= word.length(); c++)
 {
       word2 = word2.replaceFirst("@", Integer.toString(c));
 }

 return word2;
}
like image 751
CerebralCortexan Avatar asked Dec 08 '22 05:12

CerebralCortexan


2 Answers

You can use Modulus of 10 (% 10), this will wrap the count after the ninth digit to starting again.

public static String getNumberString(String s) {
        String word = s;
        String word1 = word.replaceAll("[AEIOUaeiou]", "@");
        int c = 0;

        String word2 = word1;
        for (c = 0 ; c <= word.length() ; c++) {
            word2 = word2.replaceFirst("@", Integer.toString(c % 10));
        }

        return word2;
    }

output

0b1b2b3b4b5b6b7b8b9b0b1
like image 81
Ankur Singhal Avatar answered Jan 02 '23 20:01

Ankur Singhal


How about using modulo?

word2 = word2.replaceFirst("@", Integer.toString(c % 10));
like image 27
Wajeb Avatar answered Jan 02 '23 19:01

Wajeb