0

I have a string \"Notes\":[\"

How to initialize \"Notes\":[\" to a string using JAVA?

I tried String subString1 = "\"Notes\":["; but getting only "Notes":[

Funny Boss
  • 328
  • 1
  • 3
  • 12
  • 2
    \ is an escape character, so you need to put \\ for every \ you want in a `String` so it can escape itself. You will still need to escape the double quotes with a \" as well. So \" would be \\\" instead of \". – Nexevis Jan 27 '20 at 19:59
  • Got it. It solved. String subString1 = "\\\"Notes\\\":["; is the solution. – Funny Boss Jan 27 '20 at 20:04
  • That question is for Java. I mentioned it. At the beginning i thought, I put tag Java so it will do automatically in Java section. But later I understand, I should be more specific so that it is easily understandable. So, I changed it to Java. Dont know the same syntax works for other programming language. Thanks – Funny Boss Jan 27 '20 at 20:16
  • @FunnyBoss This looks like JSON. If it is and that is what you are dealing with you should use a JSON library for easier usage instead of building such a string by yourself. Such an approach is too error-prone. – Progman Jan 27 '20 at 21:23
  • @ Progman it is not JSON. I have a big text file where I need to find that string and then need to extract data from that point to next new line of that file. So, I have to process that using JAVA. So, in Java program, I am initializing that as string and then will search on that text file. And then I will process.... – Funny Boss Jan 28 '20 at 15:07

2 Answers2

2

The initialisation String subString1 = "\"Notes\":["; is correct as it initializes it with "Notes":[.

If you want to keep the \, you'll have to add an extra \:

String subString1 = "\\\"Notes\\\":[";

If you want to have an extra double quote at the end, you can also add it:

String subString1 = "\\\"Notes\\\":[\"";

This is because \" will result in " and \\ will result in \ So, \\\" will result in \".

dan1st
  • 12,568
  • 8
  • 34
  • 67
2

Do it as follows:

public class Main {
    public static void main(String[] args) {
        String subString1 = "\\\"Notes\\\":[\\\"";
        System.out.println(subString1);
    }
}

Output:

\"Notes\":[\"

You need to escape \ as well by using another \

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110