What is the most elegant way to convert a hyphen separated word (e.g. “do-some-stuff”) to the lower camel-case variation (e.g. “doSomeStuff”)?

后端 未结 11 968
清歌不尽
清歌不尽 2020-11-28 07:16

What is the most elegant way to convert a hyphen separated word (e.g. \"do-some-stuff\") to the lower camel-case variation (e.g. \"doSomeStuff\") in Java?

11条回答
  •  臣服心动
    2020-11-28 07:48

    The following method should handle the task quite efficient in O(n). We just iterate over the characters of the xml method name, skip any '-' and capitalize chars if needed.

    public static String toJavaMethodName(String xmlmethodName) { 
      StringBuilder nameBuilder = new StringBuilder(xmlmethodName.length());    
      boolean capitalizeNextChar = false;
    
      for (char c:xmlMethodName.toCharArray()) {
        if (c == '-') {
          capitalizeNextChar = true;
          continue;
        }
        if (capitalizeNextChar) {
          nameBuilder.append(Character.toUpperCase(c));
        } else {
          nameBuilder.append(c);
        }
        capitalizeNextChar = false;
      }
      return nameBuilder.toString();
    }
    

提交回复
热议问题