Implements String.delete(char oldChar, String newChar), StringBuffer and

StringBuilder delete(int startIndex, int endIndex), and
replace (int startIndex, int endIndex, String replacementString)
This commit is contained in:
Eric Scharff 2007-10-29 15:07:36 -06:00
parent 78ee14fff5
commit bcd2c75f41
3 changed files with 52 additions and 0 deletions

View File

@ -228,6 +228,33 @@ public final class String implements Comparable<String> {
return -1; return -1;
} }
public String replace(char oldChar, char newChar) {
if (data instanceof char[]) {
char[] buf = new char[length];
for (int i=0; i < length; i++) {
if (charAt(i) == oldChar) {
buf[i] = newChar;
} else {
buf[i] = charAt(i);
}
}
return new String(buf, 0, length, false);
} else {
byte[] buf = new byte[length];
byte[] orig = (byte[])data;
byte oldByte = (byte)oldChar;
byte newByte = (byte)newChar;
for (int i=0; i < length; i++) {
if (orig[i+offset] == oldByte) {
buf[i] = newByte;
} else {
buf[i] = orig[i+offset];
}
}
return new String(buf, 0, length, false);
}
}
public String substring(int start) { public String substring(int start) {
return substring(start, length); return substring(start, length);
} }

View File

@ -60,6 +60,11 @@ public class StringBuffer {
return this; return this;
} }
public synchronized StringBuffer delete(int start, int end) {
sb.delete(start, end);
return this;
}
public synchronized StringBuffer deleteCharAt(int i) { public synchronized StringBuffer deleteCharAt(int i) {
sb.deleteCharAt(i); sb.deleteCharAt(i);
return this; return this;
@ -73,6 +78,11 @@ public class StringBuffer {
return sb.length(); return sb.length();
} }
public synchronized StringBuffer replace(int start, int end, String str) {
sb.replace(start, end, str);
return this;
}
public synchronized void setLength(int v) { public synchronized void setLength(int v) {
sb.setLength(v); sb.setLength(v);
} }

View File

@ -148,6 +148,15 @@ public class StringBuilder {
return insert(i, new String(new char[] { c }, 0, 1, false)); return insert(i, new String(new char[] { c }, 0, 1, false));
} }
public StringBuilder delete(int start, int end) {
int numChars = end - start; // Do not delete end itself
while (numChars > 0) {
deleteCharAt(start);
numChars--;
}
return this;
}
public StringBuilder deleteCharAt(int i) { public StringBuilder deleteCharAt(int i) {
if (i < 0 || i >= length) { if (i < 0 || i >= length) {
throw new IndexOutOfBoundsException(); throw new IndexOutOfBoundsException();
@ -185,6 +194,12 @@ public class StringBuilder {
return this; return this;
} }
public StringBuilder replace(int start, int end, String str) {
delete(start, end);
insert(start, str);
return this;
}
public int length() { public int length() {
return length; return length;
} }