【问题标题】:Capitalization of the words in string字符串中单词的大写
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    " foo".split(" ")
    

    你会得到一个包含两个元素的结果数组:空字符串“”和“foo”

    ["", "foo"]
    

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

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

    【讨论】:

      【解决方案3】:

      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。

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          【解决方案5】:

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


          然而,要修复您当前的代码,一种可能的解决方案是使用正则表达式作为单词 (\\w) 以及 StringBuffer/StringBuilder setCharAtCharacter.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());
          }
          

          输出:

          Test Test   Test
          

          【讨论】:

            【解决方案6】:

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

            这是一个非常优雅的解决方案,不需要 3rd 方库

                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!
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-08-06
              • 2016-02-15
              • 2023-02-03
              • 2011-05-15
              • 1970-01-01
              • 1970-01-01
              • 2011-01-20
              • 1970-01-01
              相关资源
              最近更新 更多