简体   繁体   中英

How to change a char in a String - replacing letters java

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?

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);
}

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);
}

如果你真的需要这个并且你只限于你提到的方法,那么每次找到请求的char时你都可以这样做: text = text.substring(0, i) + x + text.substring(i + 1);

将字符串转换为字符数组(包含在java API中),遍历数组并用char数组中的所有“a”替换为“x”,然后将其更改回字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM