【发布时间】:2016-09-06 18:42:44
【问题描述】:
如果字符串以空格(“”)开头或字符串中有多个空格,如何避免 StringIndexOutOfBoundsException? 实际上我需要将字符串中单词的首字母大写。
我的代码如下:
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
String[] array = s.split(" ");
for (String word : array) {
word = word.substring(0, 1).toUpperCase() + word.substring(1); //seems that here's no way to avoid extra spaces
System.out.print(word + " ");
}
}
测试:
输入:"test test test"
输出:"Test Test Test"
输入:" test test test"
输出:
StringIndexOutOfBoundsException
预期:" Test Test test"
我是 Java 新手,非常感谢任何帮助。谢谢!
【问题讨论】:
-
您可以使用
String#isEmpty检查String是否为空,如果是则什么也不做。 -
如果有的话,你可以使用 trim() 来修剪前导和尾随空格
-
把 reader.readline() 换成 reader.readline().trim() 然后试试
标签: java arrays split substring