无法使用StringBuilder将字符串连接到String

时间:2014-03-04 23:08:01

标签: java string char concatenation

这是我的代码:

public static void main(String[] args)
{
    String teacherName = "Benjamin Brown";
    int teacherSecondInitialIndex = (teacherName.indexOf(" ") + 1);
    String teacherInitials = new StringBuilder(teacherName.charAt(0)).append(teacherName.charAt(teacherSecondInitialIndex)).toString();
    System.out.println(teacherInitials);
}

我想打印出teacherName的首字母,这将是" BB"。但只有" B"正在打印出来。有什么问题?

1 个答案:

答案 0 :(得分:4)

constructor

new StringBuilder(teacherName.charAt(0))

接受int。因此,您传递的char值正在被扩展并用作StringBuilder容量,而不是基础char中的第一个String

创建一个空的StringBuilder并附加两个字符。

String teacherInitials = new StringBuilder()
        .append(teacherName.charAt(0))
        .append(teacherName.charAt(teacherSecondInitialIndex))
        .toString();