-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeleteVowels_Q9.java
More file actions
44 lines (34 loc) · 1.43 KB
/
DeleteVowels_Q9.java
File metadata and controls
44 lines (34 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
9. Write a java program to delete vowels from given string using StringBuffer class
*/
import java.util.Scanner;
public class DeleteVowels_Q9 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the string
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
// Delete vowels from the string
String result = deleteVowels_Q9(inputString);
// Display the result
System.out.println("String after removing vowels: " + result);
scanner.close();
}
// Function to delete vowels from a string using StringBuffer
private static String deleteVowels_Q9(String str) {
// Convert the string to StringBuffer for efficient modification
StringBuffer sb = new StringBuffer(str);
// Traverse the StringBuffer from end to start
// (to avoid index shifting when deleting characters)
for (int i = sb.length() - 1; i >= 0; i--) {
char ch = Character.toLowerCase(sb.charAt(i));
// Check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
// Delete the vowel
sb.deleteCharAt(i);
}
}
// Convert StringBuffer back to String and return
return sb.toString();
}
}