是否有一种不使用转义序列来生成引号的替代方法?

时间:2019-07-17 21:42:27

标签: java escaping sequence quotations

我正在尝试使我的输出在缩写和翻译的缩写周围显示双引号。但是,我没有在当前课程中介绍转义序列,因此我想知道是否还有另一种方法可以完成此任务。当我尝试转义序列时,工作簿将不接受。

我尝试了转义序列并使用两个单引号(''''),但都没有起作用。也许我缺少了一些东西,并且对Java语言来说是相当陌生的。只是从基本的角度尝试学习最有效的方法。

导入java.util.Scanner;

公共类TextMsgExpander {   公共静态void main(String [] args){

Scanner scnr = new Scanner(System.in);

String txtMsg;
String BFF = "best friend forever";
String IDK = "I don't know";
String JK = "just kidding";
String TMI = "too much information";
String TTYL = "talk to you later";

System.out.println("Enter text: ");
txtMsg = scnr.nextLine();

System.out.println("You entered: " + txtMsg);
System.out.println();

if(txtMsg.contains("BFF")) {
  txtMsg = txtMsg.replace("BFF", BFF);
  System.out.println("Replaced BFF with " + BFF);
}                    // above line is where I tried escape sequence

if(txtMsg.contains("IDK")) {
  txtMsg = txtMsg.replace("IDK", IDK);
  System.out.println("Replaced IDK with " + IDK);
}

if(txtMsg.contains("JK")) {
  txtMsg = txtMsg.replace("JK", JK);
  System.out.println("Replaced JK with " + JK);
}

System.out.println();

System.out.println("Expanded: " + txtMsg);

return;

} }

您的输出

输入文字: 您输入:IDK那是怎么回事。 TTYL。

用我不知道的替换了IDK 替换为TTYL,稍后再与您交谈

展开:我不知道那是怎么回事。待会儿再聊。

预期产量

输入文字: 您输入:IDK那是怎么回事。 TTYL。

将“ IDK”替换为“我不知道”。 将“ TTYL”替换为“稍后与您交谈”。

展开:我不知道那是怎么回事。待会儿再聊。

3 个答案:

答案 0 :(得分:0)

您尝试过吗:

\"example text\"

所以您会遇到这样的事情:

  System.out.println("Replaced \"BFF\" with " + "\"" + BFF + "\"");

  System.out.println("Replaced \"BFF\" with \"" + BFF + "\"");

答案 1 :(得分:0)

通常它应该与转义符一起使用。 您是否尝试过这样的事情:

 System.out.println("\"These two semi colons are removed when i am printed\"");

我对其进行了测试,并且对我有用。

答案 2 :(得分:0)

如果出于某种原因不能使用\转义序列,则可以使用以下事实:'撇号不需要在"xx"字符串文字中进行转义,并且不需要在"字符文字中转义'x'双引号。

例如要打印Replacing "foo" with 'bar' was easy,而foobar来自变量,则可以执行以下操作:

String s = "Replacing " + '"' + foo + '"' + " with '" + bar + "' was easy"`;
相关问题