writetocynthia
writetocynthia

Reputation: 13

Not able to escape \ in Java using \\

I have a string.

String invalid = "backslash escaping as <>:;%+\/"."

I received an error message telling me to add \ to escape the sequence. When I try to write this in Java I know that backslash needs to be escaped as \\. So I wrote it as:

String invalid = "backslash escaping as <>:;%+\\/\"."

Now this displays as backslash escaping as <>:;%+\\/".

The backslash is not escaping. How do I get only one backslash?

Upvotes: 0

Views: 876

Answers (2)

Roger
Roger

Reputation: 2952

I don't find a problem with your modification. This runs as expected:

    String invalid = "backslash escaping as <>:;%+\\/\".";
    System.out.println(invalid);

    output:
    backslash escaping as <>:;%+\/".

In your first example, you have a little problem:

\/".

Which I believe should be like this:

/\".

Because in the first way, you are closing the string before you want to. The part ." is out of the String.

Edit: try writing the output to a file or to a JTextField or something and see what happens, your string is correct and if you compare your output with my output it is the same. It might be an issue with your debugger (weird, but possible).

Upvotes: 1

Natix
Natix

Reputation: 14247

The second string in your post is correctly displayed. There must be something wrong with the way in which you observe the output.

Just try the simplest thing possible:

  • Create a file named Escape.java and write this code into its contents:

    public class Escape {
    
        public static void main(String... args) {
            String s = "backslash escaping as <>:;%+\\/\".";
            System.out.println(s);
        }
    }
    
  • Open a whatever command line that your OS provides and go to the folder with the said source file.

  • Compile the source file:

    javac Escape.java
    
  • And run the class file:

    java -cp . Escape
    
  • It should give this output:

    backslash escaping as <>:;%+\/".
    
  • ...which is exactly what you want, I believe.

Upvotes: 0

Related Questions