两个字符拼接成一个字符串
public class StringCat {
public static void main(String[] args) {
char sts0 = '0';
char sts1 = '1';
String sts3 = "0";
String sts4 = "1";
//1、问题:两个字符直接+,输出的是两个字符的ASCII码之和
String a = String.valueOf ( sts0 + sts1 );
System.out.println("a="+ a);
//2、原因:两个字符在用‘+’拼接时,返回值的是int类型,这实际是两个字符的ASCII值之和
//查看两字符的ASCII码
int asciiA = sts0;
int asciiB = sts1;
System.out.println("sts0,sts1的ASCII值分别是:"+asciiA+','+asciiB);
//3、解决方法
//(1)方法1:将两个单字符改成两个单字符串
String b = sts3 + sts4;
System.out.println("b="+ b);
//(2)方法2:用一个空的字符串去拼接两个字符
String c = "" + sts0 + sts1;
System.out.println("c="+ c);
//(3)方法3:用StringBuffer进行append--->推荐
StringBuffer strBuf = new StringBuffer();
strBuf.append(sts0);
strBuf.append(sts1);
System.out.println("d="+ strBuf);
}
}
输出:
a=97
sts0,sts1的ASCII值分别是:48,49
b=01
c=01
d=01