【发布时间】:2021-09-02 20:15:00
【问题描述】:
我正在尝试将包含连字符和下划线的字符串输入转换为驼峰式。
例子:
the-stealth-warrior
应该变成
theStealthWarrior
我以为我完全理解了这个问题,直到我在运行代码时遇到了一些奇怪的无效输出问题。
我的代码:
public class Application {
public static void main(String[] args) {
System.out.println(toCamelCase("the-stealth-warrior"));
}
public static String toCamelCase(String s) {
int sLength = s.length();
char[] camelCaseWord = new char[sLength];
int camelCaseIndex = 0;
for (int i = 0; i < sLength; i++) {
if (s.charAt(i) == '-' || s.charAt(i) == '_') {
char upper = Character.toUpperCase(s.charAt(i + 1));
camelCaseWord[camelCaseIndex] = upper;
camelCaseIndex++;
i++;
} else {
camelCaseWord[i] = s.charAt(i);
camelCaseIndex++;
}
}
return new String(camelCaseWord);
}
}
我的输出:
theS tealtW arrior
有谁知道可能是什么问题? 谢谢
【问题讨论】:
标签: java arrays string indexoutofboundsexception