You may come across a scenario where you would want to add double quotes to a String, but Java uses double quotes while initializing a String so it won't recognize that double quotes have to be added to the String.
You should have guessed what needed to be done in case you want to display double quotes with in a String in Java. Yes you need escape character "\" to escape quotes. So let's see an example.
Displaying double quotes Java example
public class SetQuote { public static void main(String[] args) { // escaping the double quotes as quotes are // needed with in the String String value = "\"Ram\""; System.out.println("Value - " + value ); } }
Output
Value - "Ram"
Let's take another example. You have got a String and you want to enclose part of it in double quotes.
For example let's say you are reading an XML in which first line has no double quotes.
Which means you got it as-
<?xml version=1.0 encoding=UTF-8?>
but it should be
<?xml version="1.0" encoding="UTF-8"?>
That can be done by using replace method of the String and escaping double quotes.
public class SetQuote { public static void main(String[] args) { SetQuote setQuote = new SetQuote(); setQuote.replaceQuote(); } public void replaceQuote(){ String xmlString = "<?xml version=1.0 encoding=UTF-8?>"; xmlString = xmlString.replace("1.0", "\"1.0\"").replace("UTF-8", "\"UTF-8\""); System.out.println("xmlString - " + xmlString); } }
Output
xmlString - <?xml version="1.0" encoding="UTF-8"?>
That's all for this topic Add Double Quotes to a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment