Replace a character at a specific index in a string?

后端 未结 8 936
我在风中等你
我在风中等你 2020-11-22 03:22

I\'m trying to replace a character at a specific index in a string.

What I\'m doing is:

String myName = \"domanokz\";
myName.charAt(4) = \'x\';
         


        
8条回答
  •  太阳男子
    2020-11-22 03:55

    I agree with Petar Ivanov but it is best if we implement in following way:

    public String replace(String str, int index, char replace){     
        if(str==null){
            return str;
        }else if(index<0 || index>=str.length()){
            return str;
        }
        char[] chars = str.toCharArray();
        chars[index] = replace;
        return String.valueOf(chars);       
    }
    

提交回复
热议问题