在另一个字符串中插入一个 Java 字符串而不连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/772988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:19:04  来源:igfitidea点击:

Inserting a Java string in another string without concatenation?

javastring

提问by me_here

Is there a more elegant way of doing this in Java?

在 Java 中是否有更优雅的方法来做到这一点?

String value1 = "Testing";  
String test = "text goes here " + value1 + " more text";

Is it possible to put the variable directly in the string and have its value evaluated?

是否可以将变量直接放入字符串并评估其值?

采纳答案by dfa

   String test = String.format("test goes here %s more text", "Testing");

is the closest thing that you could write in Java

是你可以用 Java 编写的最接近的东西

回答by Miguel Ping

What you want is called String interpolation. It is not possible in Java, although JRuby, Groovyand probably other JVM languages do that.

你想要的叫做字符串插值。这在 Java 中是不可能的,尽管JRubyGroovy和可能其他 JVM 语言可以做到这一点。



Edit: as for elegance, you can use a StringBuffer or check the other poster's solution. But at the low level, this will always be concatenation, as the other posters said.

编辑:至于优雅,您可以使用 StringBuffer 或检查其他海报的解决方案。但在低层次上,这将永远是串联,正如其他海报所说。

回答by Mnementh

It may be done by some template-libaries. But beware, Strings are immutable in Java. So in every case at some low level the concatenation will be done.

它可能由一些模板库完成。但要注意,字符串在 Java 中是不可变的。因此,在某些低级别的每种情况下,都将完成串联。

回答by Michael Myers

You'll always have to use some form of concatenation for this (assuming value1 isn't a constant like you show here).

为此,您将始终必须使用某种形式的连接(假设 value1 不是您在此处显示的常量)。

The way you've written it will implicitly construct a StringBuilderand use it to concatenate the strings. Another method is String.format(String, Object...)1, which is analogous to sprintffrom C. But even with format(), you can't avoid concatenation.

您编写它的方式将隐式构造 aStringBuilder并使用它来连接字符串。另一种方法是1,它类似于来自 C 的方法。但即使使用,也无法避免连接。String.format(String, Object...)sprintfformat()

1Yes, I know the anchor link is broken.

1是的,我知道锚链接已损坏。

回答by Pablo Santa Cruz

You can use thisfree library. It gives you sprintflike functionality. Or use String.formatstatic method provided you use Java 5 or newer.

您可以使用这个免费库。它为您提供了类似sprintf 的功能。或者使用String.format静态方法,前提是您使用 Java 5 或更新版本。

回答by toolkit

A more elegant way might be:

更优雅的方式可能是:

 String value = "Testing"; 
 String template = "text goes here %s more text";
 String result = String.format(template, value);

Or alternatively using MessageFormat:

或者也可以使用 MessageFormat:

 String template = "text goes here {0} more text";
 String result = MessageFormat.format(template, value);


Note, if you're doing this for logging, then you can avoid the cost of performing this when the log line would be below the threshold. For example with SLFJ:

请注意,如果您这样做是为了记录日志,那么当日志行低于阈值时,您可以避免执行此操作的成本。例如与SLFJ

The following two lines will yield the exact same output. However, the second form will outperform the first form by a factor of at least 30, in case of a disabled logging statement.

以下两行将产生完全相同的输出。但是,在禁用日志记录语句的情况下,第二种形式的性能将比第一种形式高出至少 30 倍。

logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);

回答by A_M

Why do you think string concatenation isn't elegant?

为什么你认为字符串连接不优雅?

If all you are doing is simple concatenation, I'd argue that code readability is more important and I'd leave it like you have it. It's more readable than using a StringBuilder.

如果你所做的只是简单的串联,我认为代码可读性更重要,我会像你一样保留它。它比使用 StringBuilder 更具可读性。

Performance won't be the problem that most people think it is.

性能不会是大多数人认为的问题。

Read this from CodingHorror

CodingHorror阅读此内容

回答by Martin Lazar

I would use a StringBuffer.. it's a common practise when you are dealing with strings. It may seem a bit when you see it for the first time, but you'll get quickly used to it..

我会使用 StringBuffer .. 这是处理字符串时的常见做法。第一次看到的时候可能会觉得有点,但是很快就会习惯的。。

String test = new StringBuffer("text goes here ").append(value1).append(" more text").toString();

Strings are immutable thus a new instance is created after every concatenation. This can cause performance issues when used in loops.

字符串是不可变的,因此在每次连接后都会创建一个新实例。在循环中使用时,这可能会导致性能问题。

StringBufferis mutable version of String- that means you can create one, modify it as you want and you have still only one instance. When desired you can get a String representation of the StringBuffer by calling it's toString()method.

StringBufferString 的可变版本- 这意味着您可以创建一个,根据需要修改它,但您仍然只有一个实例。如果需要,您可以通过调用它的toString()方法来获取 StringBuffer 的字符串表示。

回答by Tom

The problem is not if this is an elegant way or not. The idea behind using a template system may be that you put your template in a normal text file and don't have to change java code if you change your message (or think about i18ln).

问题不在于这是否是一种优雅的方式。使用模板系统背后的想法可能是您将模板放在一个普通的文本文件中,如果您更改消息(或考虑 i18ln),则不必更改 java 代码。

回答by Gelin Luo

Rythm a java template engine now released with an new feature called String interpolation modewhich allows you do something like:

Rythm 是一个 Java 模板引擎,现在发布了一个名为字符串插值模式的新功能,它允许您执行以下操作:

String result = Rythm.render("Hello @who!", "world");

The above case shows you can pass argument to template by position. Rythm also allows you to pass arguments by name:

上面的案例表明您可以按位置将参数传递给模板。Rhythm 还允许您按名称传递参数:

Map<String, Object> args = new HashMap<String, Object>();
args.put("title", "Mr.");
args.put("name", "John");
String result = Rythm.render("Hello @title @name", args);

Links:

链接: