Problemas con los caracteres certianos que causan errores de sintaxis en las cadenas

Proberly a very simple question, but within Java, I have a string as follows:

public static String wincpuload = "cmd /c @for /f "skip=1" %p in ('wmic cpu get loadpercentage') do @echo %p%";

Although I get a syntax error because of some of the charcters in the string are breaking it. Similarly in C#, if you have this kind of problem you do:

string test = @"C:\testing\test"

How can you overecome this in java?

preguntado el 01 de febrero de 12 a las 14:02

4 Respuestas

Just use a back slash (\) to escape your double quotes. Note the syntax highlighting below:

Incorrecto

String s1 = "cmd /c @for /f "skip=1" %p in ('wmic cpu get loadpercentage') do @echo %p%";

Correcto

String s2 = "cmd /c @for /f \"skip=1\" %p in ('wmic cpu get loadpercentage') do @echo %p%";

Respondido 01 Feb 12, 18:02

In Java you use \ to escape special characters in string.

Respondido 01 Feb 12, 18:02

There are no heredoc in Java, you need to escape the double quotes like this:

String wincpuload = "cmd /c @for /f \"skip=1\" %p in ('wmic cpu get loadpercentage') do @echo %p%";

Respondido 01 Feb 12, 18:02

While creating a string where you want characters like " \ you have to place another\ before those characters.

Respondido 02 Feb 12, 09:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.