题目:
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!
解析
创建一个方法say hello/sayou hello/say hello,输入一个名字、城市和州来欢迎一个人。请注意,名称将是一个由一个或多个值组成的数组,这些值应与每个值之间的一个空格连接在一起,并且测试用例中名称数组的长度将有所不同。
这个例子将返回字符串
Hello, John Smith! Welcome to Phoenix, Arizona!
本题考查对字符串操作
我的答案
public String sayHello(String [] name, String city, String state){
String str = "";
str +="Hello, ";
for(int i=0;i<name.length;i++){
if(i == name.length-1){
str+= name[i];
}else{
str+= name[i]+" ";
}
}
str += "!"+" Welcome to "+city+", "+state+"!";
return str;
}
最优答案
String.format格式化字符串 https://www.cnblogs.com/Dhouse/p/7776780.html
public String sayHello(String[] name, String city, String state){
return String.format("Hello, %s! Welcome to %s, %s!",String.join(" ", name),city,state);
}
其他答案
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," ");//用空格分隔name
return "Hello, " + str +"! Welcome to " +city +", "+ state + "!";
}
}
String.join()和StringUtils.join区别
一:是否引包
StringUtils.join() :使用前需先引入common-lang3的jar包
String.join():String.join()是JDK8新增方法(无需引包)
二:传入参数
StringUtils.join():第一个参数是传入一个任意类型数组或集合,第二个参数是拼接符
String.join():第一个参数为拼接符号,第二个参数为数组和集合
三:参数类型
StringUtils.join():可以传入Integer或者其他类型的集合或数组,
String.join():尽可以传入实现charSequence接口类型的集合或数组。