java - 返回缩写的 Get 方法

标签 java tostring

我正在编写一个简短的Java脚本,其中我将字符串中的名称作为变量。我想编写 get 方法来获取缩写并返回它们以供以后使用。该方法在打印首字母缩写时效果很好,但在想要返回该值时效果不佳。

//method for getting initials of the name
public String getInitials() {
    String words[] = competitorName.split(" "); 
    for(String word : words) { 
        return word.charAt(0) + " "; 
    } 
}

它告诉我该方法必须返回 String 类型的结果,但这应该已经是它了。即使我添加 toString 方法(然后它写它已经是 String)也不起作用

最佳答案

你差点就明白了!只需使用 StringBuilder 并返回结果

public String getInitials() {
    String words[] = competitorName.split(" ");
    StringBuilder builder = new StringBuilder();
    for(String word : words) {
        builder.append(word.charAt(0));
    }
    return builder.toString();
}

关于java - 返回缩写的 Get 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58396257/

相关文章:

java - 具有依赖注入(inject)的两个单例实例(Google Guice)

java - 如何在scala中删除java hashmap的元素?

C# - 使字符串以不同的方式打印到控制台,但以其原始形式在其他地方使用

.net - 如何使用缩写的时区显示 DateTime?

java - 如何找到图像的主色?

java - Spring MVC,使用什么 View 组件?

java - 如果语句不能正常工作

c# - TimeSpan.ToString() 上的 System.FormatException

java - toString方法我不知道如何使用它以及目的是什么

java - 原始类型int实际上如何转换为String?