【问题标题】:Split by capital letters in Java在 Java 中按大写字母分割
【发布时间】:2012-02-10 16:45:29
【问题描述】:

我需要用大写分割一个字符串,最好让后面的单词小写;

例如

ThisIsAString 变成 This is a string

谢谢

【问题讨论】:

标签: java string split


【解决方案1】:

如果你想要一个字符串,你可以这样做:

String str = "ThisIsAString";
String res = "";
for(int i = 0; i < str.length(); i++) {
   Character ch = str.charAt(i);
     if(Character.isUpperCase(ch))
       res += " " + Character.toLowerCase(ch);
     else
       res += ch;
}

【讨论】:

    【解决方案2】:

    您似乎想将驼峰式转换为可读语言。是这样吗?

    如果是这样,这个解决方案应该适合你 - How do I convert CamelCase into human-readable names in Java?

    如果您希望后续单词小写,则必须自己拆分处理。

    【讨论】:

      【解决方案3】:
      public static String cpt(String cpt){
          String new_string = "";
          for (int i=0; i < cpt.length(); i++){
              char c = cpt.charAt(i);
              if(Character.isUpperCase(c)){               
                  new_string = new_string + " " + Character.toLowerCase(c);
              }
              else {
                  new_string = new_string + c;
              }
          }
          return new_string;
      }
      

      【讨论】:

        【解决方案4】:

        使用字符大小写识别的驼峰式单词中的单词总数

        解决方案:对Hacker Rank驼峰问题:https://www.hackerrank.com/challenges/camelcase/problem

        public static void camelCaseWordWithIndexs(String s) {
        
        
            int startIndex = 0;
            int endIndex = 0;
        
            for (int i = 0; i < s.length(); i++) {
                if (Character.isUpperCase(s.charAt(i)) || i == s.length() - 1) {
                    startIndex = endIndex;
                    endIndex = i != s.length() - 1 ? i : i + 1;
                    System.out.println(s.substring(startIndex, endIndex));
                }
            }
        
        
        }
        

        【讨论】:

          猜你喜欢
          • 2021-05-15
          • 1970-01-01
          • 2012-04-21
          • 1970-01-01
          • 1970-01-01
          • 2021-04-24
          • 1970-01-01
          • 2011-07-14
          • 1970-01-01
          相关资源
          最近更新 更多