Wednesday, November 5, 2008

Replace/remove character in a String

To replace all occurences of a given character

String tmpString = myString.replace( '\'', '*' );
System.out.println( "Original = " + myString );
System.out.println( "Result = " + tmpString );

To replace a character at a specified position :

public static String replaceCharAt(String s, int pos, char c) {
return s.substring(0,pos) + c + s.substring(pos+1);
}


To remove a character :

public static String removeChar(String s, char c) {
String r = "";
for (int i = 0; i < style="font-weight: bold; color: rgb(0, 153, 0);">To remove a character at a specified position:


public static String removeCharAt(String s, int pos) {
return s.substring(0,pos)+s.substring(pos+1);
}

Chintan Patel
Peer Technology
Rajkot