Capitalization of the words in string

时间:2016-05-11 11:32:13

标签: java arrays split substring

How can I avoid of StringIndexOutOfBoundsException in case when string starts with space (" ") or when there're several spaces in the string? Actually I need to capitalize first letters of the words in the string.

My code looks like:

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 + " ");
    }
}

Tests:

Input: "test test test"

Output: "Test Test Test"


Input: " test test test"

Output:

StringIndexOutOfBoundsException

Expected: " Test Test test"

I'm a Java newbie and any help is very appreciated. Thanks!

6 个答案:

答案 0 :(得分:1)

split将尝试在找到分隔符的每个位置中断字符串。因此,如果你将空格和空格分开,如果放在字符串的开头,如

" foo".split(" ")

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

["", "foo"]

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

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

答案 1 :(得分:0)

不要拆分字符串,而是尝试简单地遍历原始字符串中的所有字符,将所有字符替换为大写字母,以防它是该字符串的第一个字符或者其前一个字符是空格。

答案 2 :(得分:0)

略微修改Capitalize first word of a sentence in a string with multiple sentences

public static void main( String[] args ) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String s = reader.readLine();

    int pos = 0;
    boolean capitalize = true;
    StringBuilder sb = new StringBuilder(s);
    while (pos < sb.length()) {
        if (sb.charAt(pos) == ' ') {
            capitalize = true;
        } else if (capitalize && !Character.isWhitespace(sb.charAt(pos))) {
            sb.setCharAt(pos, Character.toUpperCase(sb.charAt(pos)));
            capitalize = false;
        }
        pos++;
    }
    System.out.println(sb.toString());
}

我会避免使用split而改为使用StringBuilder。

答案 3 :(得分:0)

在拆分中使用正则表达式拆分所有空格

String[] words = s.split("\\s+");

答案 4 :(得分:0)

更容易使用现有的库:WordUtils.capitalize(str)(来自apache commons-lang)。

要修复当前代码,可能的解决方案是使用正则表达式(\\w)和StringBuffer / StringBuilder setCharAt和{的组合{1}}:

Character.toUpperCase

输出:

public static void main(String[] args) {
    String test = "test test   test";

    StringBuffer sb = new StringBuffer(test);
    Pattern p = Pattern.compile("\\s+\\w"); // Matches 1 or more spaces followed by 1 word
    Matcher m = p.matcher(sb);

    // Since the sentence doesn't always start with a space, we have to replace the first word manually
    sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
    while (m.find()) {
      sb.setCharAt(m.end() - 1, Character.toUpperCase(sb.charAt(m.end() - 1)));
    }

    System.out.println(sb.toString());
}

答案 5 :(得分:0)

使用原生 Java 流将字符串中的整个单词大写

这是非常优雅的解决方案,不需要第三方库

    String s = "HELLO, capitalized worlD! i am here!     ";
    CharSequence wordDelimeter = " ";

    String res = Arrays.asList(s.split(wordDelimeter.toString())).stream()
          .filter(st -> !st.isEmpty())
          .map(st -> st.toLowerCase())
          .map(st -> st.substring(0, 1).toUpperCase().concat(st.substring(1)))
          .collect(Collectors.joining(wordDelimeter.toString()));

    System.out.println(s);
    System.out.println(res);

输出是

HELLO, capitalized worlD! i am here!     
Hello, Capitalized World! I Am Here!