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

时间:2010-09-20 17:29:44

标签: java string-concatenation

我试图在Java中连接字符串。为什么这不起作用?

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

23 个答案:

答案 0 :(得分:87)

您可以使用+运算符连接字符串:

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

theNumber隐式转换为字符串"42"

答案 1 :(得分:45)

java中的连接运算符是+,而不是.

在你开始之前,

Read this(包括所有小节)。尝试停止思考php方式;)

为了扩大您在Java中使用字符串的观点 - 字符串的+运算符实际上(由编译器)转换为类似于:

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

答案 2 :(得分:14)

这个问题有两个基本答案:

  1. [simple]使用+运算符(字符串连接)。 "your number is" + theNumber + "!"(如其他地方所述)
  2. [不太简单]:使用StringBuilder(或StringBuffer)。
  3. StringBuilder value;
    value.append("your number is");
    value.append(theNumber);
    value.append("!");
    
    value.toString();
    

    我建议不要像这样堆叠操作:

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

    编辑:从java 5开始,字符串连接运算符被编译器转换为StringBuilder调用。因此,上述两种方法都是相同的。

    注意:Spaceisavaluablecommodity,asthissentancedemonstrates。

    警告:下面的示例1生成多个StringBuilder个实例,效率低于下面的示例2

    示例1

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

    示例2

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

答案 3 :(得分:7)

开箱即用,您可以 3种方式在您尝试实现时将变量值注入String

1。最简单的方法

您可以在+和任何对象或基本类型之间使用运算符String,它会自动连接String

  1. 如果是对象,则与Stringnullobj相对应的String.valueOf(obj)的值为null,否则为obj.toString()的值String.valueOf(<primitive-type>) 1}}。
  2. 如果是基本类型,则相当于null
  3. Integer theNumber = 42; System.out.println("Your number is " + theNumber + "!"); 对象的示例:

    Your number is 42!
    

    <强>输出:

    null

    Integer theNumber = null; System.out.println("Your number is " + theNumber + "!"); 对象的示例:

    Your number is null!
    

    <强>输出:

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

    原始类型示例:

    Your number is 42!
    

    <强>输出:

    String

    2。明确的方式,可能是最有效的方法

    您可以使用StringBuilder(或StringBuffer线程安全的过时对应方)使用append方法构建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)

    示例:

    Your number is 42!
    

    <强>输出:

    String

    在幕后,这实际上是最近的java编译器如何转换与运算符+完成的所有16级联,与之前方法的唯一区别在于您拥有完全控制即可。

    实际上,编译器将使用默认构造函数,因此默认容量(String)因为他们不知道构建16的最终长度是多少,这意味着如果最终长度大于String,则必须延长容量,这在性能方面具有价格。

    因此,如果您事先知道最终16的大小将大于String,那么使用此方法提供更好的初始容量会更有效率。例如,在我们的示例中,我们创建了一个长度大于16的int theNumber = 42; StringBuilder buffer = new StringBuilder(18) .append("Your number is ").append(theNumber).append('!'); System.out.println(buffer) ,因此为了获得更好的性能,应将其重写为下一个:

    优化示例:

    Your number is 42!
    

    <强>输出:

    String

    3。最可读的方式

    您可以使用String.format(locale, format, args)String.format(format, args)方法,这两种方法都依赖于Formatter来构建您的String。这允许您通过使用将被参数值替换的占位符来指定最终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); 的格式。

    示例:

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

    <强>输出:

    String

    这种方法最有趣的方面是我们清楚地知道最终{{1}}会是什么,因为它更易于阅读,因此维护起来要容易得多。

答案 4 :(得分:6)

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);

答案 5 :(得分:4)

您必须是PHP程序员。

使用+标志。

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

答案 6 :(得分:3)

为了更好地使用str1.concat(str2),其中str1str2是字符串变量。

答案 7 :(得分:3)

“+”而不是“。”

答案 8 :(得分:3)

对于两个字符串的精确连接操作,请使用:

file_names = file_names.concat(file_names1);

在您的情况下,使用+代替.

答案 9 :(得分:3)

这应该有效

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

答案 10 :(得分:3)

使用+进行字符串连接。

"Your number is " + theNumber + "!"

答案 11 :(得分:2)

在java中,连接符号是“+”。 如果您在使用jdbc时尝试连接两个或三个字符串,请使用:

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

此处“”仅用于空间。

答案 12 :(得分:1)

“+”不是“。”

但请注意String连接。这是一个介绍IBM DeveloperWorks的一些想法的链接。

答案 13 :(得分:1)

在Java中,串联符号是“+”,而不是“。”。

答案 14 :(得分:0)

第一种方法:您可以使用“+”符号连接字符串,但这总是在打印中发生。 另一种方法:String类包括一个连接两个字符串的方法:string1.concat(string2);

答案 15 :(得分:0)

import com.google.common.base.Joiner;

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

回答操作问题可能有点过头了,但了解更复杂的连接操作是件好事。这个stackoverflow问题在这个领域的一般谷歌搜索排名很高,所以很高兴知道。

答案 16 :(得分:0)

你可以使用stringbuffer,stringbuilder,就像我之前提到的每个人一样,“+”。我不确定“+”的速度有多快(我认为它对于较短的字符串来说速度最快),但是我认为构建器和缓冲区大致相同(构建器稍微快一点,因为它不同步)。

答案 17 :(得分:0)

您可以使用+运算符连接字符串:

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

输出:

hello world.

那是

答案 18 :(得分:0)

这是一个在不使用第三个变量的情况下读取和连接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);
    }
}

答案 19 :(得分:0)

有多种方法可以这样做,但是Oracle和IBM表示使用+是一种不好的做法,因为从本质上来说,每次连接String时,最终都会在内存中创建其他对象。它将利用JVM中的额外空间,并且您的程序可能空间不足或变慢。

使用StringBuilderStringBuffer是最好的选择。请查看上面的Nicolas Fillato的评论,例如与StringBuffer相关的评论。

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

答案 20 :(得分:0)

因此,从可行的答案中,您可能已经获得了为什么您的代码片段无效的答案。现在,我将添加有关如何有效执行此操作的建议。作者在article is a good place处谈到串接字符串的不同方法,还给出了各种结果之间的时间比较结果。

使用Java连接字符串的不同方式

  1. 使用+运算符(20 +“”)
  2. 通过在concat类中使用String方法
  3. 使用StringBuffer
  4. 使用StringBuilder

方法1:

这是不推荐的方法。为什么?当将它与整数和字符一起使用时,您应该非常清楚地意识到在附加字符串之前将整数转换为toString()的情况,否则它将把字符视为ASCI int的字符,并会在顶部进行加法运算。

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

//This is translated internally into,

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

方法2:

这是内部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);
}

这每次都会创建一个新缓冲区,并将旧内容复制到新分配的缓冲区中。因此,当您在更多Strings上执行时,这将太慢。

方法3:

与(1)和(2)相比,这是线程安全的并且相对较快。这在内部使用StringBuilder,并且在为缓冲区分配新的内存时(例如,当前大小为10),它将增加2 * size + 2(即22)。因此,当数组变得越来越大时,这实际上会更好地执行,因为它不需要每次为每个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;
    }

方法4

StringBuilder将是最快的String连接工具,因为它不是线程安全的。除非您非常确定使用该类的班级是单吨级,否则我强烈建议不要使用该类。

简而言之,使用StringBuffer直到不确定您的代码可以被多个线程使用。如果您确定要确定您的班级是单身人士,请继续使用StringBuilder进行串联。

答案 21 :(得分:0)

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

从Java 8和更高版本开始,我们可以使用String.join

注意:您必须传递所有StringCharSequence对象。因此,您的int变量42无法直接运行。一种选择是使用对象而不是原始对象,然后调用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.
;

转储到控制台。

System.out.println( output ) ;

请参阅此code run live at IdeOne.com

答案 22 :(得分:0)

使用“ +”符号可以连接字符串。

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