驼峰格式转换

驼峰格式转换,记录下写的比较好的:

 

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.StringBuilder;

class Solution{

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

class Solution{

  static String toCamelCase(String str){
    String[] words = str.split("[-_]");
    return Arrays.stream(words, 1, words.length)
            .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1))
            .reduce(words[0], String::concat);
  }
}

下面是我自己最初写的:

import java.lang.StringBuilder;
class Solution{

  static String toCamelCase(String s){
    String[] strArr = s.split("_|-");
    if (strArr.length == 0) {
      return s;
    }
    StringBuilder stringBuilder = new StringBuilder(strArr[0]);
    for (int i = 1; i < strArr.length; i++) {
      stringBuilder.append(strArr[i].substring(0, 1).toUpperCase()).append(strArr[i].substring(1));
    }
    return stringBuilder.toString();
  }
}

 

你可能感兴趣的:(JAVA)