Share on Google+Share on Google+

Java Remove a character from string

Advertisement
In this tutorial, you will learn how to remove a character from the string.

Java Remove a character from string

In this tutorial, you will learn how to remove a character from the string.

There are several methods for examining the content of string, finding characters or substrings within a string, changing case etc. You can manipulate the string in various ways. Here we are going to remove a particular character from the string. In the given example, we have created a method removeChar() that accepts the string and the character to remove. The for loop in this method iterates through the string and appends each character to string buffer accept the specified character. To ignore that character, we have used if statement inside the for loop that checks the existence of that character.

Example:

class RemoveCharacter{
public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer( s.length() );
r.setLength( s.length() );
int current = 0;
for (int i = 0; i < s.length(); i ++) {
char cur = s.charAt(i);
if (cur != c)
r.setCharAt( current++, cur );
}
return r.toString();
} 
public static void main(String[] args) 
{
String st="Hello World";
System.out.println("String is: "+st);
System.out.println("After removing the character r, string is: "+removeChar(st,'r'));
}
}

Output:

String is: Hello World
After removing the character r, string is: Hello Wold

Advertisements

Posted on: September 26, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.