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

题目:

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接口类型的集合或数组。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值