Reputation: 174
Simular topics were not able to solve my problem.
I need to change the char 'a'
to 'x'
in an given String str
.
Example: "abc" = "xbc". I am only allowed to use substring(), charAt()
- no replace()
method.
My code so far:
public static String ersetze(String text){
for(int i = 0; i<text.length(); i++){
if(text.substring(i, i+1).charAt(i) == 'a'){
text.substring(i, i+1) = 'x';
}
}
//return statement
}
Now the error is text.substring(i, i+1) = 'x';
that the left assignment must be a variable - clear. But how to assigne the letter to a variable now? If I declare a char x;
how to put that x
in the String to replace the letter?
Upvotes: 3
Views: 9583
Reputation: 315
String can not replace with character. First Need to create character array & then replace.
public static String ersetze(String text){
char[] result = text.toCharArray();
for(int i = 0; i < result.length; i++){
if(result [i] == 'a'){
result[i] = 'x';
}
}
return String.valueOf(result);
}
Upvotes: 5
Reputation: 10356
String
is immutable in Java, so you cannot replace a letter of a String. You need to create a new String.
You can convert the String to an array of chars and changing only the needed ones, then create a new String from this array:
public static String ersetze(String text){
char[] letters = text.toCharArray();
for (int i = 0; i < letters.length; i++){
if (letters[i] == 'a') {
letters[i] = 'x';
}
}
return new String(letters);
}
Upvotes: 5
Reputation: 353
If you REALLLLLY need this and you are limited to the methods you mentioned then you can do this each time you find requested char:
text = text.substring(0, i) + x + text.substring(i + 1);
Upvotes: 2
Reputation: 154
Convert the string to a character array (included in the java API), iterate through the array and replace all the "a"'s with "x"'s in the char array and then change it back to a string.
Upvotes: 0