0

I should write a function that excludes certain letters (char) of a sentence (String). I basically also did that but the problem is I only managed to cut out the 1st appearance of the letter in the sentence.

public static void main (String[] args) {
        String text = "This text may be readable without vowels!";
        String letters = "aeiou";
        Out.println(removeLetters(text, letters));
}
public static String removeLetters(String text, String letters) {
    char c = 'f';
    String remover = text;
    for (int i=0; i<letters.length(); i++) {
        c = letters.charAt(i);
        remover = removeChar(remover, c);
    }
    return remover;
}
public static String removeChar(String text, char c) {
    int i1 = text.indexOf(c);
    String result = text.substring(0, i1) + text.substring(i1+1);
    return result;
}

How do I need to change the last function removeChar to get all appearances of a letter cut out? It might not be that hard to find all indexes but the real struggle is to put the substrings together afterwards, so that you still only have the one sentence left just without the certain letters. Because the more indexes you have the more different substrings you need to add together if I understood it correctly.

Currently I get this.

Ths txt my be readable witht vowels!

And the aim would be to get here:

Ths txt my b rdbl witht vwls!
Dave Twickenham
  • 171
  • 1
  • 8
  • 1
    Aside: using a mutable class like `StringBuilder` would be much more efficient and possibly just easier as well. https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/StringBuilder.html – markspace Nov 27 '21 at 17:32

5 Answers5

4

And here is one way that uses a regular expression. It simply replaces each vowel in the character class [aeiou] with an empty string.

String text = "This text may be readable without vowels!";
text = text.replaceAll("[aeiou]","");
System.out.println(text);

prints

Ths txt my b rdbl wtht vwls!    
WJS
  • 36,363
  • 4
  • 24
  • 39
  • Hm, that's actually a good solution! But for that the 1st of the 2 functions would become redundant – Dave Twickenham Nov 27 '21 at 18:02
  • @DaveTwickenham that's true. Since you didn't specify them as a requirement I didn't think it would matter if they were excluded. – WJS Dec 01 '21 at 21:50
0

My suggestion is to use a loop inside the removeChar function.

Add a while loop which breaks if text.indexOf(c) returns -1 (which means that the string doesn't contain the letter you are searching for anymore).

This way you will find all occurence of each letter you want to remove from the source string.

Example code for the removeChar function:

    public static String removeChar(String text, char c) {
        String result = text;
        int i1 = text.indexOf(c);
        while (i1 != -1) {
            System.out.println("Index of " + c + " in " + result + " is: " + i1);
            String part1 = result.substring(0, i1);
            System.out.println(part1);
            String part2 = result.substring(i1+1);
            System.out.println(part2);
            result = part1 + part2;
            i1 = result.indexOf(c);
        }
        return result;
    }
Ofer Arial
  • 1,129
  • 1
  • 10
  • 25
  • How do I code this? `int i1 = text.indexOf(c); String result = ""; while (text.indexOf(c) >= 0) { result = text.substring(0, i1) + text.substring(i1+1); } return result;` with that I get nothing in the console printed out. – Dave Twickenham Nov 27 '21 at 18:11
  • 1
    In the `removeChar` function, you should address `result` and not `text` as your input string. I tried it myself - adding debug prints helps a lot in these situations. I added example code to my answer. Hope this helps. – Ofer Arial Nov 27 '21 at 18:40
  • Thx, yeah your code works in theory as I get the right result but I get a lot of additional code before that. I removed the 5th row btw because that helps getting less unwanted code out of the console. `This text my be readable without vowels! This text my be redable without vowels! This text my be redble without vowels! This txt my be redble without vowels! This txt my b redble without vowels!` and so on... it prints out every step of it. How can I avoid that, so that we only get the last sentence? Edit: Nevermind, I fixed it! – Dave Twickenham Nov 27 '21 at 18:52
0

Here are two approaches using streams:

Option 1:

You can stream the text using chars(), and then .filter() the letters:

public static String removeLetters(String text, String letters) {
    return text.chars().filter(c -> letters.indexOf(c) == -1)
            .mapToObj(Character::toString).collect(Collectors.joining());
}

Option2:

You can stream the letters using chars(), and then use .reduce() to remove the chars from text:

public static String removeLetters(String text, String letters) {
    return letters.chars().mapToObj(Character::toString)
            .reduce(text, (str, c) -> str.replaceAll(c, ""));
}

Then:

String text = "This text may be readable without vowels!";
String letters = "aeiou";
System.out.println(removeLetters(text, letters));

Output:

Ths txt my b rdbl wtht vwls!
Oboe
  • 2,643
  • 2
  • 9
  • 17
0

"Classical" variant with loop:

    public static String removeLetters(String text, String strLetters) {
        Set<Character> letters = new HashSet<>();
        for (char i : strLetters.toCharArray()) {
            letters.add(i);
        }

        StringBuilder sb = new StringBuilder();
        for (char i : text.toCharArray()) {
            if (!letters.contains(i)) sb.append(i);
        }
        return sb.toString();
    }
0xDEADBEEF
  • 131
  • 13
0

Avoid char

Other Answers use char/Character type which has been legacy since Java 2. As a 16-bit value, char is physically incapable of representing most characters.

Use code points

Instead, learn to use code point integer numbers. Each of the over 140,000 characters defined in Unicode has been permanently assigned a code point number.

List< Integer > vowelCodePoints = List.of( "aeiou".codePoints().toArray() ) ;

Get an IntStream of the code points assigned to each of the characters in your input string.

IntStream codePoints = input.codePoints() ;

Filter for the code points of characters not found in your collection of vowels’ code points.

int[] filteredCodePoints = codePoints.filter( codePoint -> ! vowelCodePoints.contains( codePoint ) ).toArray() ;

Make a String from that array of code point integers. See the Question, Generate a String object from a List of code point integers?.

String result = new String( filteredCodePoints , 0 , filteredCodePoints.length ) ;

Caveat: This code is untested, just a rough draft.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154