Reputation: 73
I have to write a method that takes in a String and returns a new string that replaces every vowel with two occurrences of that vowel.
For example: "hello" would return "heelloo"
I've experimented with my code for hours but I am not getting anything done. Here is my code:
public static String doubleVowel(String str)
{
String result = str;
for(int i = 0; i < str.length(); i++)
{
if((str.charAt(i) == 'a') ||
(str.charAt(i) == 'e') ||
(str.charAt(i) == 'i') ||
(str.charAt(i) == 'o') ||
(str.charAt(i) == 'u'))
{
result = result.substring(0, i + 1) + Character.toString(result.charAt(i))
+ result.substring(i + 1, result.length());
i++;
}
}
return result;
}
When the input is "hello", the output is "heelllo"
When the input is "computer" the output is "coomppuuter"
When the input is "sweet" the output is "sweeet"
I have racked my brain but to no avail. What is causing the bug in the program, and is there a simpler way to do this?
Upvotes: 1
Views: 5503
Reputation: 4924
You check the initial String. Working only with result right after the assignment should work.
Upvotes: 0
Reputation: 311843
I think you're over-complicating things. Instead of using substrings, just construct a result string by appending each character, or appending it twice if it's a vowel:
public static String doubleVowel(String str) {
StringBuilder result = new StringBuilder();
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
result.append(ch);
if (ch == 'a' ||
ch == 'e' ||
ch == 'i' ||
ch == 'o' ||
ch == 'u') {
result.append(ch); // second append for vowels
{
return result.toString();
}
Upvotes: 2
Reputation: 533670
Your basic problem is that you are using the same indexing for str
and result
even though after you duplicate one letter,these two strings will have different sizes and you can't use the same index any more.
It would be much simpler to build up a new StringBuilder so you don't need to maintain a second index.
StringBuilder result = new StringBuidler();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
result.append(ch); // always add the char
if ("aeiouAEIOU".indexOf(ch) >= 0)
result.append(ch); // add it again.
}
return result.toString();
This is where using a debugger would help you understand what your program is doing.
Upvotes: 1
Reputation: 7806
You are testing the character at the ith position in str but then manipulate it in result. Until result is updated for the first time it is indeed equal to str, but from then on - the two are no longer in sync...
EDIT:
Like others have pointed out - there are better ways to do this. However the question was what the bug in the program was, not what the best way to accomplish this task is :)
Upvotes: 2
Reputation: 21995
Why not just use replace?
public static String doubleVowel (String word) {
return word.replace("a", "aa")
.replace("e", "ee")
.replace("i", "ii")
.replace("o", "oo")
.replace("u", "uu");
}
Upvotes: 1