CodeWar---将字符串转换为驼峰命名

Convert string to camel case

将字符串转换为驼峰命名

自己的解法

将不是字母和数字的字符用.取代,再根据点划分数组。将下标不为0的数组首字符大写,剩下全部小写

 static String toCamelCase(String s){
    String [] arr = s.replaceAll("[^a-zA-Z0-9]+", ".").split("\\.");
    String res = "";
    for(int i=0; i< arr.length; i++){
      if(i == 0)
        res += arr[i];
      else{
        res += arr[i].substring(0,1).toUpperCase().concat(
            arr[i].substring(1).toLowerCase());
      }     
    }
    return res;
}

最佳实践

static String toCamelCase(String s){
    Matcher m = Pattern.compile("[_|-](\\w)").matcher(s);
    //[_|-]对应组0,(\\w)对应组1
    StringBuffer sb = new StringBuffer();
    while (m.find()) { 
        m.appendReplacement(sb, m.group(1).toUpperCase());
    }
    return m.appendTail(sb).toString();
}

猜你喜欢

转载自www.cnblogs.com/luo-bo/p/10597532.html
今日推荐