In this example we will describe remove any given character from a string. In this tutorial we have used StringBuilder is a mutable sequence of character. It is used as a replacement of StringBuffer.
Write a method which will remove any given character from a string?
In this example we will describe remove any given character from a string. In this tutorial we have used StringBuilder is a mutable sequence of character. It is used as a replacement of StringBuffer. StringBuilder is not synchronized and uses Formatter in case of complex string-building. The following example shows how StringBuilder is used: The majority of the modification methods on this class return this so that method calls can be chained together for example'
StringBuilder("a").append("b").append("c").toString().
Append is used along with StringBuilder as a string representation of the char argument. It checks the character you want to remove in the string in a sequence. The argument is converted into a string (in the same way as by String.valueOf(char)). Now the character in this string is appended to the character sequence.
Example of remove any given character from a string
RemoveCharFromStrinig.java
public class RemoveCharFromString { public static void main (String [] t) { System.out.println (removeCharInString ("My name is naulej kumar yadav", 'a')); } public static String removeCharInString (String string, char charToBeRemoved) { if (string == null) return ""; StringBuilder strBuild = new StringBuilder (); for (int i = 0; i < string.length (); i++) { char chr = string.charAt (i); if (chr == charToBeRemoved) continue; strBuild.append (chr); } return strBuild.toString (); } }
Output
My nme is nulej kumr ydv