Replace/remove character in a String

From CodeCodex

Implementations[edit]

Java[edit]

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 < s.length(); i ++) {
      if (s.charAt(i) != c) r += s.charAt(i);
      }
   return r;
}

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

Check this Optimize How-to for a more efficient String handling technique. New with JDK1.4, the String class offers the replaceAll() method that can be used with String or char.

 String.replaceAll("\n", "");    // Remove all \n
String.replaceAll("\n", "\r");   // Replace \n by \r

Ruby[edit]

In Ruby character type doesn't exist. It is the object of the string class. Ruby's String object is mutable.

str = "abcde'fg\nh'ij\n"
pos = 3
s = "D"

# To replace first string
str.sub('\'', '*')              # Replace first ' by * 

# To replace a character at a specified position :
str[0..pos-1] + s + str[pos+1..-1]      # new String
str[pos,1] = s                          # modify their receiver

# To remove a String
str.gsub(s, "")			# new String

# To remove a character at a specified position:
str[0..pos-1] + str[pos+1..-1]  # new String
str[pos,1] = ""                 # modify their receiver

# To replace or remove all occurences of a given string 
str.gsub("\n", "")              # Remove all \n
str.gsub("\n", "\r")            # Replace all \n by \r