简体   繁体   English

如何在 Java 中连接两个字符串?

[英]How do I concatenate two strings in Java?

I am trying to concatenate strings in Java.我正在尝试在 Java 中连接字符串。 Why isn't this working?为什么这不起作用?

public class StackOverflowTest {  
    public static void main(String args[]) {
        int theNumber = 42;
        System.out.println("Your number is " . theNumber . "!");
    }
}

You can concatenate Strings using the + operator:您可以使用+运算符连接字符串:

System.out.println("Your number is " + theNumber + "!");

theNumber is implicitly converted to the String "42" . theNumber被隐式转换为字符串"42"

The concatenation operator in java is + , not . java 中的连接运算符是+ ,而不是.

Read this (including all subsections) before you start.在开始之前阅读本文(包括所有小节)。 Try to stop thinking the php way ;)试着停止思考 php 的方式;)

To broaden your view on using strings in Java - the + operator for strings is actually transformed (by the compiler) into something similar to:为了拓宽您在 Java 中使用字符串的观点 - 字符串的+运算符实际上(由编译器)转换为类似于以下内容的内容:

new StringBuilder().append("firstString").append("secondString").toString()

There are two basic answers to this question:这个问题有两个基本答案:

  1. [simple] Use the + operator (string concatenation). [简单] 使用+运算符(字符串连接)。 "your number is" + theNumber + "!" (as noted elsewhere) (如别处所述)
  2. [less simple]: Use StringBuilder (or StringBuffer ). [不太简单]:使用StringBuilder (或StringBuffer )。
StringBuilder value;
value.append("your number is");
value.append(theNumber);
value.append("!");

value.toString();

I recommend against stacking operations like this:我建议不要像这样堆叠操作:

new StringBuilder().append("I").append("like to write").append("confusing code");

Edit: starting in java 5 the string concatenation operator is translated into StringBuilder calls by the compiler.编辑:从 java 5 开始,字符串连接运算符被编译器转换为StringBuilder调用。 Because of this, both methods above are equal.因此,上述两种方法是相同的。

Note: Spaceisavaluablecommodity,asthissentancedemonstrates.注意:空间是一种有价值的商品,正如本句所示。

Caveat: Example 1 below generates multiple StringBuilder instances and is less efficient than example 2 below警告:下面的示例 1 生成多个StringBuilder实例并且效率低于下面的示例 2

Example 1示例 1

String Blam = one + two;
Blam += three + four;
Blam += five + six;

Example 2示例 2

String Blam = one + two + three + four + five + six;

Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:当您尝试实现时,您有3 种开箱即用的方法将变量的值注入到String中:

1. The simplest way 1.最简单的方法

You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and您可以简单地在String和任何对象或原始类型之间使用运算符+ ,它会自动连接String

  1. In case of an object, the value of String.valueOf(obj) corresponding to the String " null " if obj is null otherwise the value of obj.toString() .如果是对象,则String.valueOf(obj)的值对应于Stringnull ”,如果objnull否则为obj.toString()的值。
  2. In case of a primitive type, the equivalent of String.valueOf(<primitive-type>) .在原始类型的情况下,等效于String.valueOf(<primitive-type>)

Example with a non null object:null对象示例:

Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");

Output:输出:

Your number is 42!

Example with a null object:带有null对象的示例:

Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");

Output:输出:

Your number is null!

Example with a primitive type:原始类型示例:

int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");

Output:输出:

Your number is 42!

2. The explicit way and potentially the most efficient one 2. 显式方式,可能是最有效的方式

You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.您可以使用StringBuilder (或StringBuffer线程安全过时的对应物)使用append方法构建您的String

Example:例子:

int theNumber = 42;
StringBuilder buffer = new StringBuilder()
    .append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)

Output:输出:

Your number is 42!

Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator + , the only difference with the previous way is that you have the full control .在幕后,这实际上是最近的 Java 编译器如何转换使用运算符+完成的所有String连接,与以前的方式唯一的区别是您拥有完全的控制权

Indeed, the compilers will use the default constructor so the default capacity ( 16 ) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16 , the capacity will be necessarily extended which has price in term of performances.实际上,编译器将使用默认构造函数,因此默认容量( 16 ),因为他们不知道要构建的String的最终长度是多少,这意味着如果最终长度大于16 ,则容量必然是扩展,在性能方面有价格。

So if you know in advance that the size of your final String will be greater than 16 , it will be much more efficient to use this approach to provide a better initial capacity.因此,如果您事先知道最终String的大小将大于16 ,那么使用这种方法来提供更好的初始容量会更有效率。 For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:例如,在我们的示例中,我们创建了一个长度大于 16 的String ,因此为了获得更好的性能,应该将其重写为:

Example optimized :优化示例:

int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
    .append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)

Output:输出:

Your number is 42!

3. The most readable way 3.最易读的方式

You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String .您可以使用String.format(locale, format, args)String.format(format, args) ,它们都依赖于Formatter来构建您的String This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.这允许您通过使用将被参数值替换的占位符来指定最终String的格式。

Example:例子:

int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);

Output:输出:

Your number is 42!
Your number is still 42 with printf!

The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.这种方法最有趣的方面是,我们清楚地知道最终的String是什么,因为它更易于阅读,因此更易于维护。

The java 8 way: Java 8 方式:

StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);


StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);

You must be a PHP programmer.您必须是一名 PHP 程序员。

Use a + sign.使用+号。

System.out.println("Your number is " + theNumber + "!");

For exact concatenation operation of two string please use:对于两个字符串的精确连接操作,请使用:

file_names = file_names.concat(file_names1);

In your case use + instead of .在您的情况下,请使用+而不是.

为了获得更好的性能,请使用str1.concat(str2)其中str1str2是字符串变量。

“+”代替“。”

使用+进行字符串连接。

"Your number is " + theNumber + "!"

This should work这应该工作

public class StackOverflowTest
{  
    public static void main(String args[])
    {
        int theNumber = 42;
        System.out.println("Your number is " + theNumber + "!");
    }
}

In java concatenate symbol is " + ".在java连接符号是“ + ”。 If you are trying to concatenate two or three strings while using jdbc then use this:如果您在使用 jdbc 时尝试连接两个或三个字符串,请使用以下命令:

String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);

Here "" is used for space only.这里的 "" 仅用于空格。

String.join( delimiter , stringA , stringB , … )

As of Java 8 and later, we can use String.join .从 Java 8 及更高版本开始,我们可以使用String.join

Caveat: You must pass all String or CharSequence objects.警告:您必须传递所有StringCharSequence对象。 So your int variable 42 does not work directly.所以你的int变量 42 不能直接工作。 One alternative is using an object rather than primitive, and then calling toString .一种替代方法是使用对象而不是原始对象,然后调用toString

Integer theNumber = 42;
String output = 
    String                                                   // `String` class in Java 8 and later gained the new `join` method.
    .join(                                                   // Static method on the `String` class. 
        "" ,                                                 // Delimiter.
        "Your number is " , theNumber.toString() , "!" ) ;   // A series of `String` or `CharSequence` objects that you want to join.
    )                                                        // Returns a `String` object of all the objects joined together separated by the delimiter.
;

Dump to console.转储到控制台。

System.out.println( output ) ;

See this code run live at IdeOne.com .在 IdeOne.com 上实时查看此代码

在 Java 中,连接符号是“+”,而不是“.”。

"+" not "." “+”不是“。”

But be careful with String concatenation.但要小心字符串连接。 Here's a link introducing some thoughts from IBM DeveloperWorks .这是一个介绍来自IBM DeveloperWorks 的一些想法的链接。

You can concatenate Strings using the + operator:您可以使用+运算符连接字符串:

String a="hello ";
String b="world.";
System.out.println(a+b);

Output:输出:

hello world.

That's it而已

So from the able answer's you might have got the answer for why your snippet is not working.因此,从有能力的答案中,您可能已经得到了为什么您的代码段不起作用的答案。 Now I'll add my suggestions on how to do it effectively.现在,我将添加有关如何有效执行此操作的建议。 This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.这篇文章是作者讲连接字符串的不同方式以及各种结果之间的时间比较结果的好地方

Different ways by which Strings could be concatenated in Java在 Java 中连接字符串的不同方式

  1. By using + operator (20 + "")通过使用 + 运算符 (20 + "")
  2. By using concat method in String class通过在String类中使用concat方法
  3. Using StringBuffer使用StringBuffer
  4. By using StringBuilder通过使用StringBuilder

Method 1:方法一:

This is a non-recommended way of doing.这是一种不推荐的做法。 Why?为什么? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.当您将它与整数和字符一起使用时,您应该非常注意在附加字符串之前将整数转换为toString() ,否则它会将字符视为 ASCI int 并在顶部执行加法。

String temp = "" + 200 + 'B';

//This is translated internally into,

new StringBuilder().append( "" ).append( 200 ).append('B').toString();

Method 2:方法二:

This is the inner concat method's implementation这是内部concat方法的实现

 public String concat(String str) { int olen = str.length(); if (olen == 0) { return this; } if (coder() == str.coder()) { byte[] val = this.value; byte[] oval = str.value; int len = val.length + oval.length; byte[] buf = Arrays.copyOf(val, len); System.arraycopy(oval, 0, buf, val.length, oval.length); return new String(buf, coder); } int len = length(); byte[] buf = StringUTF16.newBytesFor(len + olen); getBytes(buf, 0, UTF16); str.getBytes(buf, len, UTF16); return new String(buf, UTF16); }

This creates a new buffer each time and copies the old content to the newly allocated buffer.这每次都会创建一个新缓冲区,并将旧内容复制到新分配的缓冲区中。 So, this is would be too slow when you do it on more Strings.因此,当您在更多字符串上执行此操作时,这会太慢。

Method 3:方法三:

This is thread safe and comparatively fast compared to (1) and (2).与 (1) 和 (2) 相比,这是线程安全的并且相对较快。 This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22).这在内部使用StringBuilder ,当它为缓冲区分配新内存时(假设它的当前大小为 10),它将增加 2*size + 2(即 22)。 So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.因此,当数组变得越来越大时,这确实会表现得更好,因为它不需要每次都为每个append调用分配缓冲区大小。

 private int newCapacity(int minCapacity) { // overflow-conscious code int oldCapacity = value.length >> coder; int newCapacity = (oldCapacity << 1) + 2; if (newCapacity - minCapacity < 0) { newCapacity = minCapacity; } int SAFE_BOUND = MAX_ARRAY_SIZE >> coder; return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0) ? hugeCapacity(minCapacity) : newCapacity; } private int hugeCapacity(int minCapacity) { int SAFE_BOUND = MAX_ARRAY_SIZE >> coder; int UNSAFE_BOUND = Integer.MAX_VALUE >> coder; if (UNSAFE_BOUND - minCapacity < 0) { // overflow throw new OutOfMemoryError(); } return (minCapacity > SAFE_BOUND) ? minCapacity : SAFE_BOUND; }

Method 4方法四

StringBuilder would be the fastest one for String concatenation since it's not thread safe . StringBuilder 将是最快的String连接,因为它不是线程安全的 Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.除非您非常确定使用它的类是单吨的,否则我强烈建议不要使用这个类。

In short, use StringBuffer until you are not sure that your code could be used by multiple threads.简而言之,在您不确定您的代码是否可以被多个线程使用之前,请使用StringBuffer If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.如果您确定您的类是单例,那么继续使用StringBuilder进行连接。

First method: You could use "+" sign for concatenating strings, but this always happens in print.第一种方法:您可以使用“+”号来连接字符串,但这总是在打印时发生。 Another way: The String class includes a method for concatenating two strings: string1.concat(string2);另一种方式:String 类包含一个连接两个字符串的方法:string1.concat(string2);

import com.google.common.base.Joiner;

String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));

This may be overkill to answer the op's question, but it is good to know about for more complex join operations.这对于回答操作员的问题可能有点过头了,但是对于更复杂的连接操作,了解它是很好的。 This stackoverflow question ranks highly in general google searches in this area, so good to know.这个stackoverflow问题在该领域的一般谷歌搜索中排名很高,很高兴知道。

you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+".您可以使用 stringbuffer、stringbuilder 以及正如我之前提到的“+”。 I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).我不确定“+”有多快(我认为对于较短的字符串来说它是最快的),但是对于更长的时间,我认为 builder 和 buffer 大致相等(builder 稍微快一点,因为它不同步)。

here is an example to read and concatenate 2 string without using 3rd variable:这是一个在不使用第三个变量的情况下读取和连接 2 个字符串的示例:

public class Demo {
    public static void main(String args[]) throws Exception  {
        InputStreamReader r=new InputStreamReader(System.in);     
        BufferedReader br = new BufferedReader(r);
        System.out.println("enter your first string");
        String str1 = br.readLine();
        System.out.println("enter your second string");
        String str2 = br.readLine();
        System.out.println("concatenated string is:" + str1 + str2);
    }
}

There are multiple ways to do so, but Oracle and IBM say that using + , is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory.有多种方法可以做到这一点,但 Oracle 和 IBM 表示使用+是一种不好的做法,因为基本上每次连接 String 时,最终都会在内存中创建额外的对象。 It will utilize extra space in JVM, and your program may be out of space, or slow down.它将在 JVM 中使用额外的空间,并且您的程序可能空间不足或变慢。

Using StringBuilder or StringBuffer is best way to go with it.使用StringBuilderStringBuffer是最好的方法。 Please look at Nicolas Fillato's comment above for example related to StringBuffer .请查看上面 Nicolas Fillato 的评论,例如与StringBuffer相关的评论。

String first = "I eat";  String second = "all the rats."; 
System.out.println(first+second);

Using "+" symbol u can concatenate strings.使用“+”符号可以连接字符串。

String a="I"; 
String b="Love."; 
String c="Java.";
System.out.println(a+b+c);

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

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