How can I make Java print quotes, like “Hello”?

2019-01-02 23:31发布

How can I make Java print "Hello"?

When I type System.out.print("Hello"); the output will be Hello. What I am looking for is "Hello" with the quotes("").

13条回答
贪生不怕死
2楼-- · 2019-01-03 00:04

Adding the actual quote characters is only a tiny fraction of the problem; once you have done that, you are likely to face the real problem: what happens if the string already contains quotes, or line feeds, or other unprintable characters?

The following method will take care of everything:

public static String escapeForJava( String value, boolean quote )
{
    StringBuilder builder = new StringBuilder();
    if( quote )
        builder.append( "\"" );
    for( char c : value.toCharArray() )
    {
        if( c == '\'' )
            builder.append( "\\'" );
        else if ( c == '\"' )
            builder.append( "\\\"" );
        else if( c == '\r' )
            builder.append( "\\r" );
        else if( c == '\n' )
            builder.append( "\\n" );
        else if( c == '\t' )
            builder.append( "\\t" );
        else if( c < 32 || c >= 127 )
            builder.append( String.format( "\\u%04x", (int)c ) );
        else
            builder.append( c );
    }
    if( quote )
        builder.append( "\"" );
    return builder.toString();
}
查看更多
Juvenile、少年°
3楼-- · 2019-01-03 00:06

char ch=' " ';

System.out.println(ch+"String"+ch);

Or

System.out.println(' " '+"ASHISH"+' " ');

查看更多
Juvenile、少年°
4楼-- · 2019-01-03 00:07
System.out.println("\"Hello\"")
查看更多
走好不送
5楼-- · 2019-01-03 00:08
System.out.print("\"Hello\"");

The double quote character has to be escaped with a backslash in a Java string literal. Other characters that need special treatment include:

  • Carriage return and newline: "\r" and "\n"
  • Backslash: "\\\\"
  • Single quote: "\'"
  • Horizontal tab and form feed: "\t" and "\f"

The complete list of Java string and character literal escapes may be found in the section 3.10.6 of the JLS.

It is also worth noting that you can include arbitrary Unicode characters in your source code using Unicode escape sequences of the form "\uxxxx" where the "x"s are hexadecimal digits. However, these are different from ordinary string and character escapes in that you can use them anywhere in a Java program ... not just in string and character literals; see JLS sections 3.1, 3.2 and 3.3 for a details on the use of Unicode in Java source code.

See also:

查看更多
【Aperson】
6楼-- · 2019-01-03 00:08

Escape double-quotes in your string: "\"Hello\""

More on the topic (check 'Escape Sequences' part)

查看更多
等我变得足够好
7楼-- · 2019-01-03 00:10
android:text="import java.IO.*; \npublic class Hello \n { \nSystem.out.println(\&quot;Hello World\&quot;); \n}"
查看更多
登录 后发表回答