这是我的代码:

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”。有什么问题

最佳答案

这个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();

10-04 18:06