Removing Double Quotes from a String in Java

Hello programmers, today we will be looking on how to remove double quotes in a given string in Java.

Now, there may be several ways to do so,

One might think of iterating over the whole string, finding the double quote and then deleting it from the string, this method is also right,

but it is such a hectic task as compared to the one we will be learning in this tutorial.

So, let’s pull up our socks and get started.

Remove double quotes from a string in Java

First of all lets clear what we intend to do,

If we have a string: I will learn to “code ” today.

We want to remove the double quotes around the word “code” and make the sentence look as follows:

I will learn to code today.

 

Okay let’s get started

First of all, let’s learn about the replace() method in Java.

The replace() method

This java string method is used to replace a certain character with another character.

Syntax:

String stringName= OurString.replace("CharacterWeWantToReplace","CharacterWeWantToReplaceWith");

Here,

  • stringName: This is the string in which we want to store our new string without quotes.
  • OurString: This is the string in which we have the sentence containing double quotes.
  • CharacterWeWantToReplace: This is the character we want to replace.
  • CharacterWeWantToReplaceWith: This is the character we want to replace a certain character.

Now, you guys might think we don’t have to replace something we just need to delete the double quotes, that’s it.

But what if I tell you, we will replace double quotes with “Nothing”.

Just like this:

String str=OurString.replace("\"","");

Looks confusing?

Okay, let’s sort the things out.

Since double quotes are also interpreted differently, therefore we need to use an escape character (\) so that it is interpreted the way we want.

So, the above piece of code will replace double quotes with nothing, that simply deletes it.

Here is the full code for your reference:

import java.util.Scanner;
public class test
{
  public static void main(String args[])
  {
    
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter string");
    String str=sc.nextLine();
    System.out.println("The string you entered is:"+str);
    String str1=str.replace("\"", "");
    System.out.println("String after removing double quotes is: "+str1);
  }
}

 

Output:

 

Enter string
How are you "Coders".
The string you entered is:How are you "Coders".
String after removing double quotes is: How are you Coders.

Thanks, for reading.

Also, if there is something you don’t understand do let me know in the comments.

Happy Coding 🙂

Also, learn:

Leave a Reply

Your email address will not be published. Required fields are marked *