-1

I am trying to make a program using While to remove any letters in the String. So the string would be abcXabcXabc and I would say X and it would remove it. I.e abcabcabc. I have written most of the class but I am stumped on what I would put into my while loop.

class LineCleaner {
    private String line;
    private char remove;

    public LineCleaner(String s, char rem) {
        setCleaner(s, rem);
    }

    public void setCleaner(String s, char rem) {
        line = s;
        remove = rem
    }

    public String getCleaned() {
        String cleaned = line;
        int loc = cleaned.indexOf(remove);

        while (/*CONDITION*/) {
            // what to do here
        }
        return cleaned;
    }

    public String toString() {
        return line + " - letter to remove " + remove;
    }
}
  • 2
    Look at this question: http://stackoverflow.com/questions/13386107/java-how-to-remove-single-character-from-a-string – hic1086 Oct 28 '15 at 14:31

4 Answers4

1

There is a built in function for this already:

str = str.replace("X", "");
Ryan
  • 2,058
  • 1
  • 15
  • 29
1
String s = "abcXabcXabc";
System.out.println(s.replace("X", ""));
Rahman
  • 3,755
  • 3
  • 26
  • 43
1

Since a String is immutable, this plan of concatenating is inefficient. A StringBuilder is recommended. Then you can iterate through the original String and append only the chars that are not 'X'

StringBuilder sb = new StringBuilder();
for (char c : line.toCharArray()) {
    if (c != remove) {
        sb.append(c);
    }
}
String cleaned = sb.toString();
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
1

Another alternative is using Guava's Charmatcher ! No need to make your own class for that !

String charsToRemove = "X"; // You can remove multiple chars at the same time !
String line = "abcXabcXabc";

String cleaned = CharMatcher.anyOf(charsToRemove).removeFrom(line);

Output

abcabcabc

dguay
  • 1,635
  • 15
  • 24