简体   繁体   English

Plus运算符 - 如何强制执行字符串连接?

[英]Plus operator - How to enforce String concatenation?

While writing a Quine (ie a self-replicating program) in Java, I tried to indent output lines using tab characters: 在Java中编写Quine(即自我复制程序)时,我尝试使用制表符缩进输出行:

...
char tab = '\t';
char qm = 34;
char comma = ',';
...
System.out.println(tab + tab + tab + qm + listing[i] + qm + comma);
...

This doesn't work because the plus operator in "tab + tab + ..." adds the tab character values rather than generating a string (61 = 9 + 9 + 9 + 34): 这不起作用,因为“tab + tab + ...”中的plus运算符添加制表符字符值而不是生成字符串(61 = 9 + 9 + 9 + 34):

...
61    public static void main(String[] args) {",
...

Placing an empty string at the beginning does the job: 在开头放置一个空字符串可以完成这项工作:

...
System.out.println("" + tab + tab + tab + qm + listing[i] + qm + comma);
...

However, I can't use plain quotation marks in the Quine setting as I need to escape them to output the program text itself. 但是,我不能在Quine设置中使用简单的引号,因为我需要将它们转义为输出程序文本本身。

I wonder if it is possible to enforce the interpretation of the plus operator as String concatenation WITHOUT explicitely using quotation marks or additional Java classes? 我想知道是否可以将plus运算符的解释强制执行为字符串连接而不是明确地使用引号或其他Java类?

Do you absolutely need to use +-signs? 你绝对需要使用+ -signs吗? This'll do the trick too, and is designed for it in terms of performance: 这也是诀窍,并且在性能方面是为它而设计的:

String outputString = new StringBuilder()
    .append(tab).append(tab).append(tab).append(qm)
    .append(listing[i]).append(qm).append(comma)
    .toString();
System.out.println(outputString);

Use System.out.printf instead of System.out.println 使用System.out.printf而不是System.out.println

 char tab = '\t';
 char qm = 34;
 char comma = ',';
 System.out.printf("%c%c%c", tab, tab,comma);

You can use StringBuilder to concatenate char s to String . 您可以使用StringBuilderchar连接到String

Take a look at this answer 看看这个答案

You can replace empty quotation marks with simple String constructor: 您可以使用简单的String构造函数替换空引号:

...
System.out.println(new String() + tab + tab + tab + qm + listing[i] + qm + comma);
...

Performance pointy of view StringBuilder appending is better than String concatenation, but StringBuilder doesn't provide thread safety. 视图StringBuilder追加的性能指针优于String连接,但StringBuilder不提供线程安全性。 If you need thread safety use StringBuffer . 如果需要线程安全,请使用StringBuffer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM