0
How do I use an if statement for a string?
Bit hard to explain, but what I'm trying to do is to find how many times a certain letter(s) is in a specific string. For example: String ex = "Hello" if ('a', 'e', 'i', 'o', 'u') are in (ex) { int counter++; }
5 Antworten
+ 4
You can use a for loop and the charAt() method.
This method returns the char at a specific index.
String ex = "hello";
int counter = 0;
for(int i = 0; i < ex.length(); i++){
if(ex.charAt(i) == 'a' || ex.charAt(i) == 'e' || ex.charAt(i) == 'i' || ex.charAt(i) == 'o' || ex.charAt(i) == 'u'){
counter++;
}
}
+ 7
Here is my old code
I think this code help you
https://code.sololearn.com/cUuG8snpvKF4/?ref=app
+ 3
A recursive approach
https://code.sololearn.com/c0Axla7us3CI/?ref=app
+ 2
Are you trying to count every matching character and increment the counter or do you want to check no. Of a and show the count, no. Of e and show the count and so on.
+ 1
int counter = 0;
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
String ex = "Hello";
for(char a: vowels)
for(char b: ex.toCharArray())
if (a == b)
counter++;
System.out.print(counter);
// or
for(char a: vowels) {
for(char b: ex.toCharArray())
if (a == b)
counter++;
System.out.println(a + " " + counter);
counter = 0;
}