membersound
membersound

Reputation: 86855

How to replace characters in a fixed length string?

I'd like to replace the content of a string between specific positions with a fixed characters.

Is there any common library (apache, guava) that provides a class similar to the following pseudocode?

string.replaceBetween(10, 20, "*");

If not, how could I best achieve this with regards to performance?

Upvotes: 0

Views: 1759

Answers (2)

luchy0120
luchy0120

Reputation: 55

this is a simple implement,

 public static String replace(String old  ,int begin, int end ,char oldChar ,char newChar ){
    if (oldChar != newChar) {
    char array[] = old.toCharArray();
    for(int i = begin;i<end;i++){
        if(old.charAt(i)==oldChar){
            array[i] = newChar;
        }
    }

    return new String(array);
    }
    return old;
}

it creates a new char array ,then updates each item in the array if needed. The sad thing is ,it copies the char array again when building a new String. But ,at least,the local array will be cleaned by GC.I think this is good enough,since the origin code of JDK1.6 String replace(char oldChar,char newChar) also creates a local array as below,

public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
    int len = count;
    int i = -1;
    char[] val = value; /* avoid getfield opcode */
    int off = offset;   /* avoid getfield opcode */

    while (++i < len) {
    if (val[off + i] == oldChar) {
        break;
    }
    }
    if (i < len) {
    char buf[] = new char[len];
    for (int j = 0 ; j < i ; j++) {
        buf[j] = val[off+j];
    }
    while (i < len) {
        char c = val[off + i];
        buf[i] = (c == oldChar) ? newChar : c;
        i++;
    }
    return new String(0, len, buf);
    }
}
return this;
}  

If you read the code in StringBuffer ,you can see a lot arrayCopy,so I think the performance is not good.

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

How about following way. You can use replace() in StringBuilder.

String str = "hi, how are you?";
String alterStr=new StringBuilder(str).replace(4,6,"*").toString();
System.out.println(alterStr);

Upvotes: 5

Related Questions