public static String obify(String v) {
//String v = "AEIOU";
String result = "";
for(int i=0; i<v.length();i++) {
String x = String.valueOf(v.charAt(i));
//if a character in the string is an age,i,o,u, or y,
// then we insert a "OB" infront of the character.
// So if your string was ajp, then the output should
// be obajb. My question is why is the valueof method
// here important, are there any other alternatives?
if(x.equals("A")|| x.equals("E")|| x.equals("I")|| x.equals("O")|| x.equals("U")|| x.equals("Y")) {
result = result + "OB" + x;
}
else {
result +=x;
}
}
return result;
}
please explain why the valueOf method is important here and are there any other alternatives than using valueOf()?
174 Views Asked by AudioBubble At
3
There are 3 best solutions below
1
On
The v.charAt() methods a 'char' value and you are using the String.valueOf method to convert a 'char' value into a 'string'. Please refer to the java doc. I think this would answer your question.
As for alternatives, there are so many, but for your scenario, using a valueOf is perfectly okay, but actually the valueOf method is not required if you refactor it as follows;
public static String obify(String v) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < v.length(); i++) {
char charValue = v.charAt(i);
switch (charValue) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'Y':
result.append("OB").append(charValue);
break;
default:
result.append(charValue);
}
}
return result.toString();
}
Note that concatenation of string is also not recommended, instead in the code snippet above a "StringBuilder" is used. Also, the if statement has been replaced by a switch.
Good luck!
valueOfis converting your char to a string. You don't need to do that. You can keep it as a char, and compare the char to other chars instead of to strings. Chars are single-quoted instead of double-quoted.You can make that more concise by instead of checking if your character is equal to one of those letters using
||, you can check if it is present in a string.