【问题标题】:Is there an alternative way to generate quote marks without using the escape sequence?是否有另一种方法可以在不使用转义序列的情况下生成引号?
【发布时间】:2019-07-17 21:42:27
【问题描述】:

我试图让我的输出在缩写词和翻译的缩写词周围显示双引号。但是我没有在我目前的课程中介绍转义序列,所以我想知道是否有另一种方法来完成这个。当我尝试使用转义序列时,工作簿将不接受。

我尝试了转义序列并使用了两个单引号 ('' ''),但都没有奏效。也许我遗漏了一些东西,并且对 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”替换为“稍后再谈”。

扩展:我不知道这是怎么发生的。稍后再谈。

【问题讨论】:

  • 还有其他方法可以做到这一点,包括使用 StringBuilder 并附加 " 字符,但最有效的方法是使用 \ 转义字符:\" 是您转义的方式双引号。

标签: java escaping sequence quotations


【解决方案1】:

你试过这个吗:

\"example text\"

所以你会有这样的东西:

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

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

【讨论】:

  • 我向所有帮助之前尝试转义序列的人道歉,但我的格式不正确,但这一次成功了。感谢大家的帮助和指导。
【解决方案2】:

通常它应该与转义字符一起使用。 你有没有尝试过这样的事情:

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

我测试了它,它对我有用。

【讨论】:

    【解决方案3】:

    如果您不能使用\ 转义序列,无论出于何种原因,您都可以使用' 撇号不需要在"xx" 字符串文字中转义的事实,并且" 双-quote 不需要在 'x' 字符文字中转义。

    例如要打印Replacing "foo" with 'bar' was easyfoobar 来自变量,您可以这样做:

    String s = "Replacing " + '"' + foo + '"' + " with '" + bar + "' was easy"`;
    

    【讨论】:

      猜你喜欢
      • 2019-10-30
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      相关资源
      最近更新 更多