You are on page 1of 2

String Quetions

1)How No of Vowels in a string ?


way 1
package String1;
import java.util.*;
public class Voweldemo {
public static void main(String args[])
{
System.out.println("Enter String");
Scanner sc = new Scanner (System.in);
String str = sc.nextLine().toLowerCase();
char[] ch = str.toCharArray();

int count = 0;
for (char c : ch)
{
switch(c){
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
break;
}
}
System.out.println("No of Vowel count is " + count);
sc.close();
}
}

way 2

import java.util.Scanner;
import java.util.regex.*;

public class VowelCount {


public static void main(String[] args) {
System.out.println("Enter a string:");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
scanner.close();

// Create a regular expression pattern to match vowels (both lowercase and


uppercase)
Pattern pattern = Pattern.compile("[aeiouAEIOU]");
Matcher matcher = pattern.matcher(input);

int count = 0;
while (matcher.find()) {
count++;
}

System.out.println("Number of vowels in the string: " + count);


}
}

way 3
import java.util.Scanner;
public class Voweldemo {
public static void main(String args[]) {
System.out.println("Enter String");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine().toLowerCase();
sc.close();

String vowels = "aeiou";


int count = 0;

for (char c : str.toCharArray()) {


if (vowels.contains(String.valueOf(c))) {
count++;
}
}

System.out.println("Number of vowels in the string: " + count);


}
}

2) Write a java program to find number of words in a sentence and the corresponding
chracters?

You might also like