gpt4 book ai didi

java - 字符串中单词的大写

转载 作者:行者123 更新时间:2023-12-01 09:56:45 25 4
gpt4 key购买 nike

当字符串以空格(“”)开头或字符串中有多个空格时,如何避免 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 + " ");
}
}

测试:

输入:“测试测试测试”

输出:“测试测试测试”

<小时/>

输入:“测试测试测试”

输出:

StringIndexOutOfBoundsException

预期:“测试测试测试”

我是 Java 新手,非常感谢任何帮助。谢谢!

最佳答案

split 将尝试在找到分隔符的每个位置中断字符串。因此,如果您按空格分割,并且将空格放置在字符串的开头,例如

" foo".split(" ")

您将得到结果数组,其中包含两个元素:空字符串“”和“foo”

["", "foo"]

现在,当您调用 "".substring(0,1)"".substring(1) 时,您正在使用索引 1它不属于该字符串。

因此,在根据索引进行任何字符串修改之前,请通过测试字符串长度来检查它是否安全。因此,请检查您尝试修改的单词的长度是否大于 0,或者使用更具描述性的内容,例如 if(!word.isEmpty())

关于java - 字符串中单词的大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37161364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com