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?
CodePudding user response:
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);
CodePudding user response:
There are two variants of String.replace
:
String String.replace(char, char)
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.
CodePudding user response:
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);
CodePudding user response:
A String is an immutable object. If you need to manipulate it, then you should use a StringBuilder
.
The problem with your code is that you're attempting to pass the int i
to the replace
method which accepts two characters not an int and a character. The method replaces every occurrence of the first character passed with the second one, which is not what you want. What you're trying to do is to replace the character at position i with an empty String which is wrong again as an empty String is not a character. Besides, the condition to make sure that only vowels can stay should be made with && not with ||. Finally, your 'o' character is actually a '0'.
This is a fixed version of your code using a StringBuilder.
public class Test {
public static void main(String[] args) {
int count = 0;
System.out.println("Enter a sentence :");
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();
StringBuilder strBuilder = new StringBuilder(sentence);
for (int i = 0; i < strBuilder.length(); i ) {
char ch = strBuilder.charAt(i);
if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') {
//Remove the current not-vowel
strBuilder.deleteCharAt(i);
//decreasing the index i so that previous i 1 letter, which is now in position i, won't be skipped in the next iteration since i will be incremented at the end of this one
i--;
}
}
String sentence_edited = strBuilder.toString();
System.out.println(sentence_edited);
}
}