Zitrone
Zitrone

Reputation: 79

Replace a character in a String?

i have a problem with replacing a specific character in a string with another string. The problem is that i can figure out to remove the old character and i get the character and the string next to each other. here is what i did until now.

public class zeichenErsetzen {
public static String ersetzeZeichen(String w,char b,String v){
    String ersetzt="" ;
    for(int i=0;i<w.length();i++){
        ersetzt += w.charAt(i);
        if(w.charAt(i)==b)
            ersetzt +=v ;
    }
    return ersetzt;
}
public static void main(String []args){
    String str = "Dies ist ein i";

    System.out.println(ersetzeZeichen(str, 'i', "ast"));
}

}

This is what i get i use this

Diastes iastst eiastn iast

and this is how it is supposed to be

Dastes astst eastn ast

Upvotes: 0

Views: 90

Answers (2)

QBrute
QBrute

Reputation: 4536

Your problem lies here:

ersetzt += w.charAt(i);
if(w.charAt(i)==b)
    ersetzt +=v;

You're adding each letter, regardless if it is the one you want to replace. Add an additional else to fix this.

if(w.charAt(i)==b) {
    ersetzt +=v;
}
else {
    ersetzt += w.charAt(i);
}

Now a letter is added only if it doesn't match the one you want to replace.

Upvotes: 1

Use the StringBuilder class

    final String hello = "Hello";
    final StringBuilder sb = new StringBuilder(hello);
    sb.setCharAt(0, 'x');

    System.out.println("New String after replace: " + sb.toString());

Upvotes: 0

Related Questions