I want to insert an "ab" before every vowel in a word
Example, if the user enters the word: fire it has to be changed to: fabirabe but my code is only entering the ab before the word like: abfire. How can I fix that?
Here's my code so far:
import java.util.Scanner;
public class Foothill
{
// class variables shared by more than one method
String prompt;
static String strUserResponse;
// main method
public static void main (String[] args)
{
giveInstructions();
getUserInput();
convertToTurkeyIrish();
vowelCounter();
}
public static String convertToTurkeyIrish()
{
String turkeyIrish = strUserResponse;
String turkeyIrish2;
turkeyIrish2 = "ab" + strUserResponse.replaceAll("(aeiouAEIOU)", "$1ab");
System.out.println("Word In Turkey Irish: " + turkeyIrish2);
return turkeyIrish;
}
public static void vowelCounter()
{
int vowel = 0;
strUserResponse.length();
char vowels;
vowels = ' ';
for (int j = 0; j <= strUserResponse.length() - 1 ; j++)
{
vowels = strUserResponse.charAt(j);
if ((vowels == 'a') || (vowels == 'A') || (vowels == 'e') || (vowel == 'E') || (vowel == 'i')|| (vowels == 'I') || (vowels == 'o') (vowels == 'O') || (vowel == 'u') || (vowels == 'u'))
{
System.out.println("Vowels in " + strUserResponse + ": " + vowel++);
}
}
}
}
答案 0 :(得分:1)
Your regex is wrong, and so is the replace string. Try this:
strUserResponse.replaceAll("([aeiouAEIOU])", "ab$1");
答案 1 :(得分:1)
Change your regex to:
(?i)(a|e|i|o|u)
and the replacement to:
ab$1
Your current regex is aeiouAEIOU
which matches a sequence of characters: "aeiouAEIOU".
Test it:
System.out.println("fire".replaceAll("(?i)(a|e|i|o|u)", "ab$1"));
// fabirabe
Or as suggested by @amit, you can simply use a character class and write [aeiou]
. Note that I used the (?i)
to indicate that the regex should be case insensitive.