Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8236030

Cleanup use of String.toCharArray

    Details

      Description

      Utils has the following couple of methods: removeLeadingWhitespace and removeTrailingWhitespace. Both unconditionally call toCharArray, which will return a *copy* of the underlying character content.

      At a minimum, it may be better to do a one-off check of the first or last character, so see if the character array is actually needed; it may also be desirable just to iterate over the string characters instead of over a copy of the characters. Presumably the amount of leading or trailing whitespace is typically small compared to the rest of the content.
        
          private String removeTrailingWhitespace(String text) {
              char[] buf = text.toCharArray();
              for (int i = buf.length - 1; i > 0 ; i--) {
                  if (!Character.isWhitespace(buf[i]))
                      return text.substring(0, i + 1);
              }
              return text;
          }

          private String removeLeadingWhitespace(String text) {
              char[] buf = text.toCharArray();
              for (int i = 0; i < buf.length; i++) {
                  if (!Character.isWhitespace(buf[i])) {
                      return text.substring(i);
                  }
              }
              return text;
          }

        Attachments

          Activity

            People

            • Assignee:
              jjg Jonathan Gibbons
              Reporter:
              jjg Jonathan Gibbons
            • Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: