How to remove double quotes characters from a string using Java

The double quotes characters in a string object in java can be removed by copying the string in a new String without adding the double quote characters.

Call the following method:

public static String removeDoubleQuotes(String input){

	StringBuilder sb = new StringBuilder();
	
	char[] tab = input.toCharArray();
	for( char current : tab ){
    	if( current != '"' )
    		sb.append( current );	
	}
	
	return sb.toString();
}

The method first creates a StringBuilder object that will contain the output String. The input String is converted to an array to facilitate the process. The array is analysed using a for loop: if the current character is not a double quotes, that character is added to the output String. If the current character is a double quotes it is omitted. The output String is then returned.

Create the following java file:

public class StringRemoveDoubleQuotes {

    public static String removeDoubleQuotes(String input){

	StringBuilder sb = new StringBuilder();
	
	char[] tab = input.toCharArray();
	for( char current : tab ){
	    if( current != '"' )
		sb.append( current );	
	}
	
	return sb.toString();
    }

    public static void main(String[] argv) {

	String test = "This is a \"test \" ";

	String output = removeDoubleQuotes( test );
	
	System.out.println( test + " => " + output );
    }
}

The output will be:

This is a "test "  => This is a test  

In the example, we create an array of characters so the code is easier to understand. That step can be skipped and the array created directly in the for loop. This will remove the tab variable and the char array will be defined in a smaller context.

How to remove double quotes from a string in Java

References:

java io

Recent Comments