我想用eyesOfTiger替换例如“eyes-of-tiger”,但我不知道确切的解决方案。
如何用大写字母替换“-”?
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();
}
}
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]);
}
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
Try this:
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();
试试这个通用解决方案:
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);
}