Ruslan Pylypyuk
Ruslan Pylypyuk

Reputation: 57

How to remove characters from the String

I want to delete all letters except vowels from the string entered by user.

I used this code:

System.out.println("Enter a sentence :");
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();
            
for (int i= 0; i < sentence.length(); i ++) {
    char ch = sentence.charAt(i);
    if (ch != 'a' || ch !='e' || ch !='i' || ch != '0' || ch != 'u' ) {
        String sentence_edited = sentence.replace(i,"");
    }
}
System.out.println(sentence_edited);

But it gives a compilation error.

How could I fix it?

Upvotes: 1

Views: 2475

Answers (3)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 28988

The compiler clearly tells you that the method signature of the replace() doesn't match because you are a trying to pass an index i as the first argument. Instead, you probably wanted to pass a String containing a character under the index i.

Note that a version of the replace(char, char) method that expects two character values would not be useful for that task. Because it's meant to replace a character with another character, and you can't remove any characters from the string with it.

But that isn't the only issue with your code.

Condition ch != 'a' || ch !='e' || ch !='i'... etc. is not correct. You should use logical && here instead of or ||.

Variable sentence_edited exists only in the scope of if-statement where it was defined. And doesn't make sense to apply sentence.replace(String.valueOf(ch),"") in a loop because sentence remains unchanged (reminder: strings are immutable in Java). And even if you would reassign the variable sentence, then it'll mess the order of iteration, and you'll get an incorrect result.

Here is a couple of better way to approach this problem.

replaceAll()

You can remove all characters except vowels in one line by making use of replaceAll() method:

String sentence = sentence.replaceAll("[^aeiou]", "");

This method expects a regular expression as the first argument (for more information on regular expressions, take a look at this tutorial)

StringBuilder & Set

If for some reason you need to utilize a loop for that purpose, you can define a Set containing all vowels or a String as shown below if you're not comfortable with collections. And check every character in the user input against the set of vowels.

All characters that will pass the condition will get appended to the instance of StringBuilder, which represents a mutable string in Java. You can easily transform it into a String by invoking toString() on it.

String sentence = sc.nextLine();
StringBuilder sentenceEdited = new StringBuilder();

String vowels = "aeiou"; // or Set<Character> vowels = Set.of('a', 'e', 'i', 'o', 'u');
        
for (int i= 0; i < sentence.length(); i++) {
    char ch = sentence.charAt(i);
    if (vowels.contains(String.valueOf(ch))) {
        sentenceEdited.append(ch);
    }
}
System.out.println(sentenceEdited);

Upvotes: 2

Samir Maliqi
Samir Maliqi

Reputation: 51

Hmm... Here is your code with few fixes. You need to check if we are dealing with any of the vowels instead (== and not !=) and also no additional string is required.

int count = 0;
    System.out.println("Enter a sentence :");
    Scanner sc = new Scanner(System.in);
    String sentence = sc.nextLine();
    
    for (int i= 0; i < sentence.length(); i ++)
    {
        char ch = sentence.charAt(i);
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == '0' || ch == 'u' ) {
            sentence = sentence.substring(0, i) + sentence.substring(i+1);
        }
    }
    System.out.println(sentence);

Upvotes: 0

cyberbrain
cyberbrain

Reputation: 5075

There are two variants of String.replace:

  1. String String.replace(char, char)
  2. String String.replace(CharSequence, CharSequence)

Your code tries to call something like String.replace(int, CharSequence), but such a method does not exist. String does not have a method to replace the char at position n.

I suggest that you put your String into a StringBuilder first and then use StringBuilder.deleteCharAt(int). Finally you get a String out of the cleaned StringBuilder with its .toString() method.

Upvotes: 0

Related Questions