如何在java中连接字符? [英] How to concatenate characters in java?

查看:162
本文介绍了如何在java中连接字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在java中连接字符?连接字符串在字符串之间只需要一个 + ,但使用 + 连接字符会将char的值更改为ascii并因此给出数字输出。我想做 System.out.println(char1 + char2 + char3 ... ,并创建一个类似这样的String字符。



我可以做

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



感谢

 字符串s = new StringBuilder()。append(char1).append(char2).append(char3).toString(); 

请注意

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

实际编译为

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

编辑:如litb指出,您也可以这样做:

 + char1 + char2 + char3; 

编译成以下内容:

  new StringBuilder()。append()。append(c).append(c1).append(c2).toString 

编辑(2):修正字符串追加比较,作为cletus点out,一系列字符串由编译器处理。



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

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.

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.

Thanks

解决方案

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:

"" + 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.

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

这篇关于如何在java中连接字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆