开发者社区 问答 正文

java 常用方法 normalizeSpace

Remove leading and trailing whitespace and then replacing sequences of whitespace characters.

public static String normalizeSpace(String str) {

}
要求:需要运行速度快

展开
收起
蛮大人123 2016-02-26 16:23:24 2581 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪
      public static final String EMPTY_STRING = "";
         public static String normalizeSpace(String str) {
            if (null == str) {
                return null;
            }
    
            if (EMPTY_STRING == str) {
                return EMPTY_STRING;
            }
    
            int length = str.length();
            int start = 0, end = length;
            while ((str.charAt(start) == ' ' && start < length)) {
                start++;
            }
            if (start == end) {
                return EMPTY_STRING;
            }
            while ((end > start) && str.charAt(end - 1) == ' ') {
                end--;
            };
    
            if (start == end) {
                return EMPTY_STRING;
            }
    
            StringBuilder buf = new StringBuilder(end - start);
            boolean sawEmptyChar = false;
            char tempChar = 0;
            for (int i = start; i < end; i++) {
                tempChar = str.charAt(i);
                if (tempChar == ' ') {
                    if (!sawEmptyChar) {
                        sawEmptyChar = true;
                        buf.append(' ');
                    }
                } else {
                    sawEmptyChar = false;
                    buf.append(tempChar);
                }
            }
            return buf.toString();
        }
    2019-07-17 18:48:22
    赞同 展开评论
问答分类:
问答标签:
问答地址: