How to enter quotes in a Java string?

我与影子孤独终老i 提交于 2019-11-25 22:46:31

问题


I want to initialize a String in Java, but that string needs to include quotes; for example: \"ROM\". I tried doing:

String value = \" \"ROM\" \";

but that doesn\'t work. How can I include \"s within a string?


回答1:


In Java, you can escape quotes with \:

String value = " \"ROM\" ";



回答2:


In reference to your comment after Ian Henry's answer, I'm not quite 100% sure I understand what you are asking.

If it is about getting double quote marks added into a string, you can concatenate the double quotes into your string, for example:

String theFirst = "Java Programming";
String ROM = "\"" + theFirst + "\"";

Or, if you want to do it with one String variable, it would be:

String ROM = "Java Programming";
ROM = "\"" + ROM + "\"";

Of course, this actually replaces the original ROM, since Java Strings are immutable.

If you are wanting to do something like turn the variable name into a String, you can't do that in Java, AFAIK.




回答3:


Not sure what language you're using (you didn't specify), but you should be able to "escape" the quotation mark character with a backslash: "\"ROM\""




回答4:


Just escape the quotes:

String value = "\"ROM\"";



回答5:


\ = \\

" = \"

new line = \r\n OR \n\r OR \n (depends on OS) bun usualy \n enough.

taabulator = \t




回答6:


In Java, you can use char value with ":

char quotes ='"';

String strVar=quotes+"ROM"+quotes;



回答7:


Look into this one ... call from anywhere you want.

public String setdoubleQuote(String myText) {
    String quoteText = "";
    if (!myText.isEmpty()) {
        quoteText = "\"" + myText + "\"";
    }
    return quoteText;
}

apply double quotes to non empty dynamic string. Hope this is helpful.




回答8:


Here is full java example:-

public class QuoteInJava {     

public static void main (String args[])
    {
            System.out.println ("If you need to 'quote' in Java");
            System.out.println ("you can use single \' or double \" quote");
    }
}

Here is Out PUT:-

If you need to 'quote' in Java
you can use single ' or double " quote




回答9:


suppose ROM is string variable which equals "strval" you can simply do

String value= " \" "+ROM+" \" ";

it will be stored as

value= " "strval" ";    


来源:https://stackoverflow.com/questions/3559063/how-to-enter-quotes-in-a-java-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!