替换" - "与大写字母

时间:2013-06-11 14:38:03

标签: java regex eclipse

我想用eyesOfTiger替换“老虎眼”,但我不知道确切的解决方案。

如何用大写字母代替“ - ”?

5 个答案:

答案 0 :(得分:7)

public class Test {

    public static void main(String[] args) {

        String input = "eye-of-tiger";
        String modified = dashToUpperCase(input);
        System.out.println(modified);
    }

    private static String dashToUpperCase(String input) {

        StringBuilder result = new StringBuilder();
        boolean toUpper = false;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '-') {
                toUpper = true;
            } else {
                result.append(toUpper ? Character.toUpperCase(c) : c);
                toUpper = false;
            }
        }

        return result.toString();
    }
}

答案 1 :(得分:1)

String str="eyes-of-tiger";
String[] strTokens = str.split("-");
str=strTokens[0];
for(int i=1;i<strTokens.length;i++)
{
    str+= StringUtils.capitalize(strTokens[i]);
}

答案 2 :(得分:1)

public static void main(String[] args) {
    String coolSong = "eye-of-the-tiger";
    String[] words = coolSong.split(("-"));
    StringBuilder result = new StringBuilder();

    result.append(words[0]);
    for (int i = 1; i < words.length; i++) {
        words[i] = words[i].substring(0, 1).toUpperCase()
                + words[i].substring(1, words[i].length());
        result.append(words[i]);
    }

    System.out.println(result.toString());

}

输出:

eyeOfTheTiger

答案 3 :(得分:0)

尝试使用此通用解决方案:

String[] split = s.split("-");
    for(int i = 0; i < split.length; i++){
        split[i] = split[i].substring(0, 1).toUpperCase() + split[i].substring(1).toLowerCase();
    }

    StringBuilder builder = new StringBuilder();
    for(String string : split) {
        builder.append(string);
    }

答案 4 :(得分:0)

试试这个:

    String s = "eyes-of-tiger";
    StringBuilder newString = new StringBuilder();
    String[] arr = s.split("-");
    boolean first = true;
    for (String str : arr) {
        if (first) {
            newString.append(str);
            first = false; 
            continue;
        }
        newString.append((str.substring(0,1).toUpperCase()) + str.substring(1));
    }
    String result = newString.toString();