`.concat()` 与 `String.valueOf` 结合使用无法正常工作。

huangapple go评论63阅读模式
英文:

.concat() is not working with String.valueOf

问题

/**
 * 获取姓名的缩写。
 *
 * @return 姓名的缩写。
 */
public String initials() 
{
   String result = name.substring(0, 1);
   for (int i = 0; i < name.length() - 1; i++)
   {
        if(name.charAt(i) == ' ')
        {
           result = result.concat(String.valueOf(name.charAt(i + 1)));
        }
    }
  return result;
}

测试代码如下,调用 initials 方法后,仅返回 'J':

Name name = new Name("John Jacob Jingleheimer Schmidt");
System.out.println(name.initials());
System.out.println("Expected: JJJS");

在这种编码方式下,将转换后的字符连接到字符串后仍无法正常连接到结果,仅返回姓名的首字母。

英文:
/**
 * Gets the initials of the name .
 * 
 * @return the initials of the name.
 */public String initials() 
{
   String result = name.substring(0, 1);
   for (int i = 0; i &lt; name.length() - 1; i++)
   {
        if(name.charAt(i) == &#39; &#39;)
        {
           result.concat(String.valueOf(name.charAt(i + 1)));
        }
    }
  return result;
 }

The tester is below which only returns 'J' after calling the initials method:

Name name = new Name(&quot;John Jacob Jingleheimer Schmidt&quot;);
System.out.println(name.initials());
System.out.println(&quot;Expected: JJJS&quot;);

When I write the code in this way, the following char after converted to String still cannot concat after the result, and only returns the first letter of the name.

答案1

得分: 3

String是一个不可变类,即String#concat会创建一个新的String,你需要将其赋值回结果,如下所示:

result = result.concat(String.valueOf(name.charAt(i + 1)));
英文:

String is an immutable class i.e. String#concat creates a new String which you need to assign back to result as shown below:

result = result.concat(String.valueOf(name.charAt(i + 1)));

huangapple
  • 本文由 发表于 2020年10月10日 01:58:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64285058.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定