0

There is a piece of text which contains a lot of double quotes:

"fdfdfs"sdf)sdfds*fsd"/fsdfsd\"f""we"r32ed**s(fsdF"sdF"s'sfsD"FSD"'f"'SD"FsD"f'"sdF"Sf'Sf"S

And now I want to assign it to a String variable in Java. What should I do? I know backslash may work, but what if the text contains thousands of double quotes? In python, I can use single quote or triple quotes to easily handle this issue. Is there any similar method in Java (and in Android Studio) to fix this issue?

Edit: I want to copy the text, and directly "drop"(paste) it into a String.Just like in Python I can satisfy the requirements by just a pair of triple quotes:

String s= 
a="""
"fdfdfs"sdf)sdfds*fsd"/fsdfsd\"f""we"r32ed**s(fsdF"sdF"s'sfsD"FSD"'f"'SD"FsD"f'"sdF"Sf'Sf"S
"""
print(a) # outcome:"fdfdfs"sdf)sdfds*fsd"/fsdfsd\"f""we"r32ed**s(fsdF"sdF"s'sfsD"FSD"'f"'SD"FsD"f'"sdF"Sf'Sf"S
Edric
  • 24,639
  • 13
  • 81
  • 91
vainquit
  • 491
  • 6
  • 13
  • "*And now I want to assign it to a String variable in Java*" - in what way? Copy-paste? Read from file? – Fureeish Jan 11 '20 at 01:53
  • @Fureeish I prefer to a Copy-paste method, since I may have to deal with a lot of such texts, which will be pretty unconvinient if I do it in the "reading from file" way. – vainquit Jan 11 '20 at 02:18
  • The above suggested similar questions can partly answer my question. I may adopt those solutions if I have to. But I would like to see something more convinient and new ways if possible, since those answers were posted 2 years ago. – vainquit Jan 11 '20 at 02:22
  • 2
    I believe that any decent IDE should automatically escape any quotes directly copy-pasted into a String. IntelliJ does so, at least. – Fureeish Jan 11 '20 at 02:24
  • @Fureeish You are right! I just find those texts can be printed out as I expect......My wrong. It seems that I misunderstood the concept of "escape". Thank you ! – vainquit Jan 11 '20 at 02:43
  • If you have text with thousands of characters, you are better off putting it in a text file and reading that file as a resource. I don’t see much benefit to having a string literal of that size in code. – VGR Jan 11 '20 at 03:18

1 Answers1

2

Java 13 has a preview feature called Text Blocks which allow exactly* that:

String s = """
           <your text here>
           """;

You'll have to enable preview features for that and the feature may or may not change in future versions.

In earlier versions of Java there is no such functionality.

*Well, mostly. Text blocks are not really raw strings but allow double quotes at least.

Marvin
  • 13,325
  • 3
  • 51
  • 57