Home Java Beginners Write a method which will remove any given character from a string?
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Write a method which will remove any given character from a string?

Advertisement
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

Download Source Code

Advertisement

Liked it!  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.

Posted on: July 5, 2013

Ask Questions?    Discuss: Write a method which will remove any given character from a string?  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com