5 Replies Latest reply: Dec 22, 2009 8:23 AM by 800387 RSS

    First character of a string to lowercase

    843789
      I want to rewrite the first character of a string to lowercase and I strongly suspect that there's a better/easier way of doing it than this rather elaborate way I figured (being a real beginner):
      char [] nameInChars = token[x].toCharArray();
      char lower = Character.toLowerCase(nameInChars[0]);
      String nameEdit = token[x].replace(token[x].charAt(0), ' ');
      String nameTrimmed = nameEdit.trim();
      String nameLowerCase = new StringBuilder().append(lower).append(nameTrimmed).toString();
      Suggestions would be much appreciated!

      Edited by: Igor_Pavlove on Dec 22, 2009 5:45 AM
        • 1. Re: First character of a string to lowercase
          800387
          public final String asLowerCaseFirstChar(final String target) {
          
             if ((target == null) || (target.length() == 0)) {
                 return target;  // You could omit this check and simply live with an exception if you like
             }
             return Charater.toLowerCase(target.chartAt(0)) + (target.length() > 1 ? target.substring(1) : "");
          }
          - Saish
          • 2. Re: First character of a string to lowercase
            843789
            Thanks man!
            Looks better indeed.
            • 3. Re: First character of a string to lowercase
              800387
              Igor_Pavlove wrote:
              I want to rewrite the first character of a string to lowercase and I strongly suspect that there's a better/easier way of doing it than this rather elaborate way I figured (being a real beginner):
              char [] nameInChars = token[x].toCharArray();
              char lower = Character.toLowerCase(nameInChars[0]);
              String nameEdit = token[x].replace(token[x].charAt(0), ' ');
              I'm really not sure why you did the third line above. The first two lines would be okay, if you were looking through each character and building the string using a StringBuilder.
              String nameTrimmed = nameEdit.trim();
              String nameLowerCase = new StringBuilder().append(lower).append(nameTrimmed).toString();
              Using StringBuilder is a good idea, but as long as you are not creating strings in a loop, you can safely use the plus-sign for concatenation.
              Suggestions would be much appreciated!
              
              Edited by: Igor_Pavlove on Dec 22, 2009 5:45 AM
              - Saish
              • 4. Re: First character of a string to lowercase
                843789
                What's the philosophy behind the fact that you prefer
                 (target.length() > 1 ? target.substring(1) : "");
                to
                target.substring(1);
                ?
                • 5. Re: First character of a string to lowercase
                  800387
                  Fair enough.

                  - Saish