Resetting a variable to zero during a loop
I have this code that allows me to take a string and replace all vowels with an ever increasing number.
For example, "abababababababababababa" will give me "0b1b2b3b4b5b6b7b8b9b10b11". I'm trying to store it in such a way that the number, when it has passed 9, resets to zero and starts counting again (so that "0b1b2b3b4b5b6b7b8b9b10b11" reads "0b1b2b3b4b5b6b7b8b9b0b1" instead).
I can't figure out how to do this in a loop, which isn't quite confusing. If there is some way to achieve this that someone doesn't mind disclosing, 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;
}
You can use Modulus of 10 (% 10)
this will return the count after the ninth digit to start over.
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
How about using modulo?
word2 = word2.replaceFirst("@", Integer.toString(c % 10));
As a loop, you can use another variable other than c
, as provided, if you can check when c
will become 9
and reset to 0
.
public static String getNumberString( String s)
{
String word = s;
String word1 = word.replaceAll("[AEIOUaeiou]", "@");
int c = 0;
String word2 = word1;
for(int i = 0; i <= word.length(); i++)
{
word2 = word2.replaceFirst("@", Integer.toString(c));
if(c == 9) {
c = 0;
} else {
c++;
}
}
return word2;
}
Try using the ten module. It will cycle through because when it reaches a multiple of ten, the modulus will be 0 again.
instead of replacing with c, you can use c % 10
In your loop, you can do
for (c = 0; c <= word.length(); c = (c + 1) % 10) {...}
I would use String.toCharArray()
. You can use % 10
to ensure that it count
turns after the ninth digit. Also, I would use StringBuilder
. Something like,
public static String getNumberString(String str) {
int count = 0;
StringBuilder sb = new StringBuilder();
if (str != null) {
for (char ch : str.toCharArray()) {
switch (Character.toLowerCase(ch)) {
case 'a': case 'e': case 'i': case 'o': case 'u':
sb.append(count);
++count;
count %= 10;
// or maybe, count = (count > 9) ? 0 : count;
break;
default:
sb.append(ch);
}
}
}
return sb.toString();
}
Then you can check it like
public static void main(String[] args) {
String out = getNumberString("abababababababababababa");
String expected = "0b1b2b3b4b5b6b7b8b9b0b1";
System.out.println(out.equals(expected));
}
Output
true
you should use c% 10 instead of c like this code:
word2 = word2.replaceFirst("@", Integer.toString(c % 10));