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++; }

10th Nov 2019, 7:14 PM
Jacob
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++; } }
10th Nov 2019, 7:23 PM
Denise Roßberg
Denise Roßberg - avatar
+ 7
Here is my old code I think this code help you https://code.sololearn.com/cUuG8snpvKF4/?ref=app
10th Nov 2019, 7:19 PM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
10th Nov 2019, 7:36 PM
Michael
Michael - avatar
+ 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.
10th Nov 2019, 7:20 PM
Avinesh
Avinesh - avatar
+ 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; }
10th Nov 2019, 7:50 PM
rodwynnejones
rodwynnejones - avatar