Our task for the last few weeks has been to create a simple program that replaces vowels in a String input with something else (I've chosen the letter "z", because, you know, "zzzz..."). You can find my code below:
import java.util.Scanner;
class VowelReplacer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for (char c : vowels) {
// System.out.println("Value of c: " + c);
string = string.replace(c, 'z');
// System.out.println(string);
}
System.out.println(string);
}
}
And here's a program that removes all occurrences of a user-specified String from a String input:
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class StringRemover {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please type a word or sentence:");
String stringToChange = scanner.nextLine();
Pattern pattern = Pattern.compile(stringToChange);
System.out.println("Please type a String:");
String stringToRemove = scanner.nextLine();
Matcher matcher = pattern.matcher(stringToChange);
if (matcher.find()) {
stringToChange = stringToChange.replaceAll(stringToRemove, "");
}
System.out.println("Resulting String is \"" + stringToChange + "\"");
}
}
Please note that the second of these two programs has one major limitation - it's case-sensitive.
No comments:
Post a Comment