这是我的代码:
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”。有什么问题
最佳答案
new StringBuilder(teacherName.charAt(0))
接受
int
。因此,您传递的char
值将被扩展并用作StringBuilder
容量,而不是用作基础char
中的第一个String
。创建一个空的
StringBuilder
并追加两个字符。String teacherInitials = new StringBuilder()
.append(teacherName.charAt(0))
.append(teacherName.charAt(teacherSecondInitialIndex))
.toString();