Java Remove a character from string


 

Java Remove a character from string

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

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

Ads