Reputation: 83
I want to make an array to search for vowels in a string something like umm
public class letstrythis{
public static void main(string[]arg){
String[] myStringArray = [1];
String[] myStringArray = {"iwanttotryifthisworks"};
String myStringArray = new String[] {"iwanttotryifthisworks};
if(string=a,e,i,o,u;
for (int i=0;i< string.length; i++){
int intvalue = string[i];
system.out.println(i);
)
}
}
Question, what's the function to search the string for vowels?
Upvotes: 0
Views: 8348
Reputation: 5781
If you don't want to loop, you could always use a regular express.
import java.util.regex.Matcher; import java.util.regex.Pattern;
public class Regex {
public static void main(String[] args) {
Pattern p = Pattern.compile("[aeiou]", Pattern.CASE_INSENSITIVE);
String s = "iwanttotryifthisworks";
Matcher m = p.matcher(s);
int i = 0;
while (m.find()) i++;
System.out.println("Matches: " + i);
}
}
There's a looping for m.find(), but it's not a bunch of loops.
Upvotes: 1
Reputation: 83
import java.util.Scanner;
public class Countingvowel {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char letter;
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
count++;
}
}
System.out.printf("There are %d occurrences of %s in %s", count, letter, sentence);
}
}
Upvotes: 1
Reputation: 8008
iterate over the array and increase the count when you see a vowel. you can keep all the vowels in a Set. There is no built in function to do this.
Set<Character> vowels = new HashSet<Character>();
vowels.add('a');vowels.add('e');vowels.add('i');vowels.add('o');vowels.add('u');
String input = new String("any input string");
int count=0;
for (int i=0 ; i<input.size() ; i++)
{
if(vowels.contains(input.charAt(i)))
count++;
}
System.out.println(count);
or with char array
Set<Character> vowels = new HashSet<Character>();
vowels.add('a');vowels.add('e');vowels.add('i');vowels.add('o');vowels.add('u');
String inp = new String("any input string");
char[] input = inp.toCharArray();
int count=0;
for (int i=0 ; i<input.length ; i++)
{
if(vowels.contains(input[i]))
count++;
}
System.out.println(count);
Upvotes: 1
Reputation: 464
public class CountVowels {
public static void main(String[] args) {
String string = "this is a test string for counting vowels";
int count = 0;
for (int i = 0;i < string.length();i++) {
if (isVowel(string.charAt(i)))
count++;
}
System.out.println(count);
}
public static boolean isVowel(char ch) {
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
}
Upvotes: 1