【问题标题】:Invalid characters in String字符串中的无效字符
【发布时间】:2021-09-02 20:15:00
【问题描述】:

我正在尝试将包含连字符和下划线的字符串输入转换为驼峰式。

例子:

the-stealth-warrior

应该变成

theStealthWarrior

我以为我完全理解了这个问题,直到我在运行代码时遇到了一些奇怪的无效输出问题。

我的代码:

public class Application {
    public static void main(String[] args) {
        System.out.println(toCamelCase("the-stealth-warrior"));
    }

    public static String toCamelCase(String s) {
        int sLength = s.length();

        char[] camelCaseWord = new char[sLength];
        int camelCaseIndex = 0;

        for (int i = 0; i < sLength; i++) {
            if (s.charAt(i) == '-' || s.charAt(i) == '_') {
                char upper = Character.toUpperCase(s.charAt(i + 1));
                camelCaseWord[camelCaseIndex] = upper;
                camelCaseIndex++;
                i++;
            } else {
                camelCaseWord[i] = s.charAt(i);
                camelCaseIndex++;
            }
        }
        return new String(camelCaseWord);
    }
}

我的输出:

theS tealtW  arrior

有谁知道可能是什么问题? 谢谢

【问题讨论】:

    标签: java arrays string indexoutofboundsexception


    【解决方案1】:

    改成

    camelCaseWord[camelCaseIndex] = s.charAt(i);
    

    你也应该检查一下

    char upper = Character.toUpperCase(s.charAt(i + 1));
    

    在连字符或下划线位于字符串末尾的情况下,确保它不超过字符串的边界

    【讨论】:

      【解决方案2】:

      你也可以这样做(我认为它不那么复杂):

         private static void covertToCamelCase(String s) {
          String camelCaseString = "";
          for(int i = 0; i < s.length(); i++){
              if(s.charAt(i) == '_' || s.charAt(i) == '-'){
                  
                  // if  hyphen or underscore is at the beggining
                  if(i == 0) {
                      camelCaseString += s.toLowerCase().charAt(i+1);
                  }  // if  hyphen or underscore is at the end
                  else if(i != s.length()-1) {
                      camelCaseString += s.toUpperCase().charAt(i + 1);
                  }
      
                  i++;
              }else{
                  camelCaseString += s.charAt(i);
              }
          }
      
          System.out.println(camelCaseString);
      }
      

      当你运行代码时

       public static void main(String[] args) {
          covertToCamelCase("test_test");
          covertToCamelCase("some-new-string-word");
          covertToCamelCase("hyphen-at-end-");
          covertToCamelCase("-hyphen-at-beginning-");
      }
      

      输出将是:

      testTest
      someNewStringWord
      hyphenAtEnd
      hyphenAtBeginning
      

      【讨论】:

      • 谢谢!我看到你的逻辑,这是有道理的。仍然不能 100% 确定为什么我的错误。
      • 问题出在 else 语句中。就像可怕的袋熊写的那样,你应该改变 camelCaseWord[i] = s.charAt(i); to camelCaseWord[camelCaseIndex] = s.charAt(i);
      猜你喜欢
      • 2021-07-22
      • 2017-02-02
      • 1970-01-01
      • 2011-03-04
      • 2013-12-20
      • 1970-01-01
      • 2014-03-09
      相关资源
      最近更新 更多