1 package javax.xml.bind; 2 3 8 abstract class WhiteSpaceProcessor { 9 10 28 public static String replace(String text) { 29 return replace( (CharSequence )text ).toString(); 30 } 31 32 35 public static CharSequence replace(CharSequence text) { 36 int i=text.length()-1; 37 38 while( i>=0 && !isWhiteSpaceExceptSpace(text.charAt(i)) ) 40 i--; 41 42 if( i<0 ) 43 return text; 45 46 StringBuilder buf = new StringBuilder (text); 49 50 buf.setCharAt(i--,' '); 51 for( ; i>=0; i-- ) 52 if( isWhiteSpaceExceptSpace(buf.charAt(i))) 53 buf.setCharAt(i,' '); 54 55 return new String (buf); 56 } 57 58 62 public static CharSequence trim(CharSequence text) { 63 int len = text.length(); 64 int start = 0; 65 66 while( start<len && isWhiteSpace(text.charAt(start)) ) 67 start++; 68 69 int end = len-1; 70 71 while( end>start && isWhiteSpace(text.charAt(end)) ) 72 end--; 73 74 if(start==0 && end==len-1) 75 return text; else 77 return text.subSequence(start,end+1); 78 } 79 80 public static String collapse(String text) { 81 return collapse( (CharSequence )text ).toString(); 82 } 83 84 89 public static CharSequence collapse(CharSequence text) { 90 int len = text.length(); 91 92 int s=0; 96 while(s<len) { 97 if(isWhiteSpace(text.charAt(s))) 98 break; 99 s++; 100 } 101 if(s==len) 102 return text; 104 105 108 StringBuilder result = new StringBuilder (len ); 109 110 if(s!=0) { 111 for( int i=0; i<s; i++ ) 112 result.append(text.charAt(i)); 113 result.append(' '); 114 } 115 116 boolean inStripMode = true; 117 for (int i = s+1; i < len; i++) { 118 char ch = text.charAt(i); 119 boolean b = isWhiteSpace(ch); 120 if (inStripMode && b) 121 continue; 123 inStripMode = b; 124 if (inStripMode) 125 result.append(' '); 126 else 127 result.append(ch); 128 } 129 130 len = result.length(); 132 if (len > 0 && result.charAt(len - 1) == ' ') 133 result.setLength(len - 1); 134 138 return result; 139 } 140 141 144 public static final boolean isWhiteSpace(CharSequence s) { 145 for( int i=s.length()-1; i>=0; i-- ) 146 if(!isWhiteSpace(s.charAt(i))) 147 return false; 148 return true; 149 } 150 151 152 public static final boolean isWhiteSpace(char ch) { 153 if( ch>0x20 ) return false; 156 157 return ch == 0x9 || ch == 0xA || ch == 0xD || ch == 0x20; 159 } 160 161 165 protected static final boolean isWhiteSpaceExceptSpace(char ch) { 166 if( ch>=0x20 ) return false; 169 170 return ch == 0x9 || ch == 0xA || ch == 0xD; 172 } 173 } 174 | Popular Tags |