120k views
4 votes
How would I do this code with a while loop to remove the letters? Please and thank you

How would I do this code with a while loop to remove the letters? Please and thank-example-1
User Laquana
by
6.2k points

1 Answer

1 vote

There is of course a replace() function in java that lets you do this without a while loop. If you want to do it letter by letter, it gets a little complicated because you have to take care not to index the string outside its bounds.

I did not bother to create a separate runner class. The Main is just inside this class and everything is static.

public class LetterRemover {

public static String RemoveLetters(String s, char c)

{

int loc = s.indexOf(c);

while(loc >= 0)

{

if (loc == 0) {

s = s.substring(1);

} else if (loc == s.length()-1) {

s = s.substring(0, loc);

} else {

s = s.substring(0, loc) + s.substring(loc+1);

}

loc = s.indexOf(c);

}

return s;

}

public static void Test(String s, char c) {

System.out.format("%s - letter to remove %c\\%s\\", s, c, RemoveLetters(s,c));

}

public static void main(String[] args) {

Test("I am Sam I am", 'a');

Test("ssssssssxssssesssssesss", 's');

Test("qwertyqwertyqwerty", 'a');

}

}

User Noam Solovechick
by
6.6k points