如何在java中连接字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/328249/
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 13:13:52  来源:igfitidea点击:

How to concatenate characters in java?

javacharacterconcatenation

提问by

How do you concatenate characters in java? Concatenating strings would only require a +between the strings, but concatenating chars using +will change the value of the char into ascii and hence giving a numerical output. I want to do System.out.println(char1+char2+char3...and create a String word like this.

你如何连接java中的字符?连接字符串只需要+字符串之间的a ,但是连接字符 using+会将字符的值更改为 ascii 并因此给出数字输出。我想做System.out.println(char1+char2+char3...并创建一个像这样的字符串词。

I could do

我可以

System.out.print(char1);
System.out.print(char2);
System.out.print(char3);

But, this will only get me the characters in 1 line. I need it as a string. Any help would be appreciated.

但是,这只会让我得到 1 行中的字符。我需要它作为一个字符串。任何帮助,将不胜感激。

Thanks

谢谢

回答by Dustin

Do you want to make a string out of them?

你想用它们做一根绳子吗?

String s = new StringBuilder().append(char1).append(char2).append(char3).toString();

Note that

注意

String b = "b";
String s = "a" + b + "c";

Actually compiles to

实际上编译为

String s = new StringBuilder("a").append(b).append("c").toString();

Edit: as litb pointed out, you can also do this:

编辑:正如 litb 指出的,你也可以这样做:

"" + char1 + char2 + char3;

That compiles to the following:

编译为以下内容:

new StringBuilder().append("").append(c).append(c1).append(c2).toString();

Edit (2): Corrected string append comparison since, as cletus points out, a series of strings is handled by the compiler.

编辑 (2):更正了字符串追加比较,因为正如 cletus 指出的那样,一系列字符串由编译器处理。

The purpose of the above is to illustrate what the compiler does, not to tell you what you should do.

上面的目的是为了说明编译器做了什么,而不是告诉你你应该做什么。

回答by Ewen Cartwright

You need a String object of some description to hold your array of concatenated chars, since the chartype will hold only a single character. e.g.,

您需要一个具有某种描述的 String 对象来保存您的串联字符数组,因为该char类型将只保存一个字符。例如,

StringBuilder sb = new StringBuilder('a').append('b').append('c');
System.out.println(sb.toString);

回答by sblundy

You need to tell the compiler you want to do String concatenation by starting the sequence with a string, even an empty one. Like so:

您需要通过以字符串开头的序列(甚至是空字符串)来告诉编译器您想要进行字符串连接。像这样:

System.out.println("" + char1 + char2 + char3...);

回答by Johannes Schaub - litb

If you have a bunch of chars and want to concat them into a string, why not do

如果您有一堆字符并想将它们连接成一个字符串,为什么不这样做

System.out.println("" + char1 + char2 + char3); 

?

?

回答by cletus

I wasn't going to answer this question but there are two answers here (that are getting voted up!) that are just plain wrong. Consider these expressions:

我不打算回答这个问题,但这里有两个答案(正在投票!)完全是错误的。考虑这些表达式:

String a = "a" + "b" + "c";
String b = System.getProperty("blah") + "b";

The first is evaluated at compile-time. The second is evaluated at run-time.

第一个在compile-time进行评估。第二个是在运行时评估的。

So neverreplace constant concatenations (of any type) with StringBuilder, StringBuffer or the like. Only use those where variables are invovled and generally only when you're appending a lot of operands or you're appending in a loop.

所以永远不要用 StringBuilder、StringBuffer 或类似的东西替换常量连接(任何类型的)。仅使用那些涉及变量的变量,并且通常仅在您附加大量操作数或在循环中附加时使用。

If the characters are constant, this is fine:

如果字符是恒定的,这很好:

String s = "" + 'a' + 'b' + 'c';

If however they aren't, consider this:

但是,如果它们不是,请考虑:

String concat(char... chars) {
  if (chars.length == 0) {
    return "";
  }
  StringBuilder s = new StringBuilder(chars.length);
  for (char c : chars) {
    s.append(c);
  }
  return s.toString();
}

as an appropriate solution.

作为适当的解决方案。

However some might be tempted to optimise:

然而,有些人可能会想要优化:

String s = "Name: '" + name + "'"; // String name;

into this:

进入这个:

String s = new StringBuilder().append("Name: ").append(name).append("'").toString();

While this is well-intentioned, the bottom line is DON'T.

虽然这是善意的,但底线是不要

Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.

为什么?正如另一个答案正确指出的那样:编译器会为您执行此操作。因此,在自己做时,您不允许编译器优化代码或不取决于它是否是一个好主意,代码更难阅读并且不必要地复杂。

For low-level optimisation the compiler is better at optimising code than you are.

对于低级优化,编译器比您更擅长优化代码。

Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.

让编译器完成它的工作。在这种情况下,最坏的情况是编译器隐式地将您的代码更改为您编写的代码。连接 2-3 个字符串可能比构造 StringBuilder 更有效,因此最好保持原样。编译器知道在这方面什么是最好的。

回答by Dennis C

You can use the String constructor.

您可以使用String 构造函数

System.out.println(new String(new char[]{a,b,c}));

回答by Dennis C

public class initials {

公开课首字母{

public static void main (String [] args) {

    char initialA = 'M';
    char initialB = 'P';
    char initialC = 'T';

    System.out.println("" + initialA + initialB + initialC );


}   

}

}

回答by Elvis

System.out.println(char1+""+char2+char3)

or

或者

String s = char1+""+char2+char3;

回答by Arun.R

System.out.print(a + "" + b + "" + c);

回答by Aky

I don't really consider myself a Java programmer, but just thought I'd add it here "for completeness"; using the (C-inspired) String.formatstatic method:

我并不真正认为自己是 Java 程序员,但只是想“为了完整性”将其添加到此处;使用(C 启发)String.format静态方法:

String s = String.format("%s%s", 'a', 'b'); // s is "ab"