codewars解题笔记---Welcome to the City

Instructions:

Create a method sayHello/say_hello/SayHello that takes as input a name, city, and state to welcome a person. Note that name will be an array consisting of one or more values that should be joined together with one space betweeen each, and the length of the name array in test cases will vary.

Example:

sayHello(new String[]{“John”, “Smith”}, “Phoenix”, “Arizona”)

This example will return the string Hello, John Smith! Welcome to Phoenix, Arizona!

Sample Tests:

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class HelloTest {
    
    @Test
    public void test1() throws Exception {
        Hello h = new Hello();
        String[] name = {"John", "Smith"};
        assertEquals("Hello, John Smith! Welcome to Phoenix, Arizona!",
          h.sayHello(name, "Phoenix", "Arizona"));
    }
}

Solution:

public class Hello{
  public String sayHello(String [] name, String city, String state){
    //code here
  }
}

题目解说:

创建一个方法say hello/sayou hello/say hello,输入一个名字、城市和州来欢迎一个人。请注意,名称将是一个由一个或多个值组成的数组,这些值应与每个值之间的一个空格连接在一起,并且测试用例中名称数组的长度将有所不同。
例子:

sayHello(new String[]{“John”, “Smith”}, “Phoenix”, “Arizona”)

这个例子将返回字符串hello,john smith!欢迎来到亚利桑那州凤凰城!

我的答案:

import org.apache.commons.lang3.StringUtils;
public class Hello{
  public String sayHello(String [] name, String city, String state){
    //code here
    String str = StringUtils.join(name," ");
    return "Hello, " + str +"! Welcome to " +city +", "+ state + "!";
  }
}

最优答案:

public class Hello{
  public String sayHello(String[] name, String city, String state){
    return String.format("Hello, %s! Welcome to %s, %s!",String.join(" ", name),city,state);
  }
}

你可能感兴趣的:(codewars)