Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String use quotes without escape character

I know that it is possible to write double quotes in Java strings by putting \ symbol before them. But if double quotes are used a lot in a string, is there a way to mark the string once, so there won't be a need to write the \ symbol before each? (just like in C#, it is possible to put the @ symbol before the string) Example:

String quotes = @"""""""""""""""""""";

instead of

String quotes = "\"\"\"\"\"\"\"\"\"\"\"";
like image 800
Victor2748 Avatar asked Oct 17 '14 01:10

Victor2748


People also ask

How do I stop characters from escaping in Java?

However, we know that the backslash character is an escape character in Java String literals as well. Therefore, we need to double the backslash character when using it to precede any character (including the \ character itself).

Can I use single quotes for string in Java?

A string literal is bracketed by either single quotes ( ' ) or double quotes ( " ). When single quotes bracket a string literal, the value of the literal is the value within the quotes. When double quotes are used, any references to variables or expressions within the quotes are interpolated.

How do you keep quotes in a string Java?

Add double quotes to String in java If you want to add double quotes(") to String, then you can use String's replace() method to replace double quote(") with double quote preceded by backslash(\").

How do you escape a double quote in a string in Java?

The first method to print the double quotes with the string uses an escape sequence, which is a backslash ( \ ) with a character. It is sometimes also called an escape character.


3 Answers

You can't. But if you are too lazy to escape each of the double quotes, there are some trick that can do that. For example:

String quotes = "....................".replace(".","\"");
System.out.println(quotes);

output: """"""""""""""""""""

like image 155
DnR Avatar answered Oct 23 '22 22:10

DnR


No, there is no such way to write a String literal with unescaped quotes.

You can write the text externally and load it at runtime.

like image 23
Sotirios Delimanolis Avatar answered Oct 23 '22 22:10

Sotirios Delimanolis


There is no way to escape all subsequent double quotes in code (that I know of). But, I recommend against hard-coding String literals. Instead, I suggest you use a ResourceBundle (or even Properties). One benefit being you don't have to escape String(s) you read in that way.

like image 29
Elliott Frisch Avatar answered Oct 23 '22 22:10

Elliott Frisch