android开发字符串工具类
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android开发字符串工具类相关的知识,希望对你有一定的参考价值。
1 package com.gzcivil.utils; 2 3 import java.io.BufferedReader; 4 import java.io.ByteArrayOutputStream; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.math.BigDecimal; 8 import java.text.SimpleDateFormat; 9 import java.util.Arrays; 10 import java.util.Calendar; 11 import java.util.Date; 12 import java.util.Locale; 13 import java.util.StringTokenizer; 14 import java.util.regex.Matcher; 15 import java.util.regex.Pattern; 16 17 /** 18 * 字符串工具 19 * 20 * @author LiJinlun 21 * @time 2015-12-5 22 */ 23 public class StringUtils { 24 25 private static StringUtils instance; 26 27 private StringUtils() { 28 super(); 29 } 30 31 public static String getDateTimeToString(Calendar cal, String format) { 32 return getDateTimeToString(cal.getTimeInMillis(), format); 33 } 34 35 public static String getDateTimeToString(long longTime, String format) { 36 SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault()); 37 Date date = new Date(longTime); 38 return sdf.format(date); 39 } 40 41 public static synchronized StringUtils getInstance() { 42 if (instance == null) 43 instance = new StringUtils(); 44 return instance; 45 } 46 47 /** 将一个字符串从第一位开始截取到有数字出现的地方 */ 48 public static String clearNumberString(String str) { 49 int minIndex = Integer.MAX_VALUE; 50 int[] index = new int[10]; 51 for (int i = 0; i < 10; i++) { 52 index[i] = str.indexOf(String.valueOf(i)); 53 if (index[i] != -1 && index[i] < minIndex) { 54 minIndex = index[i]; 55 } 56 } 57 if (minIndex < Integer.MAX_VALUE) { 58 str = str.substring(0, minIndex); 59 } 60 return str; 61 } 62 63 /** 64 * 判断字符串是否为空 65 */ 66 public static boolean isEmpty(String str) { 67 return null == str || str.trim().equals(""); 68 } 69 70 /** 71 * 描述:手机号格式验证. 72 * 73 * @param str 74 * 指定的手机号码字符串 75 * @return 是否为手机号码格式:是为true,否则false 76 */ 77 public static Boolean isMobilePhone(String str) { 78 Boolean isMobileNo = false; 79 try { 80 Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$"); 81 Matcher m = p.matcher(str); 82 isMobileNo = m.matches(); 83 } catch (Exception e) { 84 e.printStackTrace(); 85 } 86 return isMobileNo; 87 } 88 89 /** 90 * 获取字串字节长度 91 * 92 * @param str 93 * @return 94 */ 95 public static int getLength(String str) { 96 return str.replaceAll("[^\\x00-\\xff]", "**").trim().length(); 97 } 98 99 /** 返回double数据d小数点后面2位有效数字 */ 100 public static double getDouble(double d) { 101 return new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); 102 } 103 104 /** 从double型返回String型,精确到小数点后2位 */ 105 public static String getStringByDouble(double d) { 106 String str = String.valueOf(new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()); 107 try { 108 int index = str.indexOf(‘.‘); 109 if (index != -1) { 110 String tmpStr = str.substring(index + 1); 111 if ("0".equals(tmpStr)) { 112 str = str.substring(0, index); 113 } 114 } 115 } catch (Exception e) { 116 e.printStackTrace(); 117 } 118 return str; 119 } 120 121 public static String getCorrectDistance(int distance) { 122 String result = ""; 123 if (distance < 20) { 124 result = "附近"; 125 } else if (distance < 1000) { 126 result = distance + "m"; 127 } else { 128 result = String.format("%.1f", distance / 1000f) + "km"; 129 } 130 return result; 131 } 132 133 /** 134 * 将秒数转换成文字描述 135 * 136 * @param tm单位秒 137 */ 138 public static String secondsToString(int tm) { 139 if (tm <= 0) 140 return "00:00:00"; 141 long hour = tm / 3600; 142 tm = tm % 3600; 143 long min = tm / 60; 144 tm = tm % 60; 145 146 String result = ""; 147 if (hour < 10) { 148 result = "0" + hour + ":"; 149 } else { 150 result = String.valueOf(hour) + ":"; 151 } 152 153 if (min < 10) { 154 result += "0" + min + ":"; 155 } else { 156 result += min + ":"; 157 } 158 159 if (tm < 10) { 160 result += "0" + tm; 161 } else { 162 result += String.valueOf(tm); 163 } 164 return result; 165 } 166 167 /** 168 * 检测是否JSON字串 169 * 170 * @param source 171 * @return 172 */ 173 public static boolean isJson(String source) { 174 String tmp = null == source ? "" : source.trim(); 175 if ("".equals(tmp) || tmp.length() < 1) 176 return false; 177 else if (tmp.startsWith("{") && tmp.endsWith("}")) 178 return true; 179 else if (tmp.startsWith("[") && tmp.endsWith("]")) 180 return true; 181 else 182 return false; 183 } 184 185 public static String str2int(String source) { 186 String result = ""; 187 LogUtils.i("ls", "result" + result); 188 for (int i = 0; i < source.length(); i++) { 189 if (source.charAt(i) >= ‘0‘ && source.charAt(i) <= ‘9‘) 190 result += source.charAt(i); 191 192 } 193 return result; 194 } 195 196 /** 197 * MD5编码 198 * 199 * @param source 200 * @return 201 */ 202 public static String md5(byte[] source) { 203 char hexDigits[] = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘ }; 204 try { 205 java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); 206 md.update(source); 207 byte tmp[] = md.digest(); 208 char str[] = new char[16 * 2]; 209 for (int i = 0, k = 0; i < 16; i++) { 210 byte byte0 = tmp[i]; 211 str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 212 str[k++] = hexDigits[byte0 & 0xf]; 213 } 214 return new String(str); 215 } catch (Exception e) { 216 LogUtils.e("md5(): error=" + e.getMessage(), "StringTool"); 217 return ""; 218 } 219 } 220 221 /** 222 * base64编码,将字节数组编码为字符串 223 * 224 * @param source 225 * @return String 226 */ 227 public static String base64_encode(byte[] source) { 228 char[] base64EncodeChars = new char[] { ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘, ‘I‘, ‘J‘, ‘K‘, ‘L‘, ‘M‘, ‘N‘, ‘O‘, ‘P‘, ‘Q‘, ‘R‘, ‘S‘, ‘T‘, ‘U‘, ‘V‘, ‘W‘, ‘X‘, ‘Y‘, ‘Z‘, ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘, ‘i‘, ‘j‘, ‘k‘, ‘l‘, ‘m‘, ‘n‘, ‘o‘, ‘p‘, ‘q‘, ‘r‘, ‘s‘, ‘t‘, ‘u‘, ‘v‘, ‘w‘, ‘x‘, ‘y‘, ‘z‘, ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘+‘, ‘/‘ }; 229 try { 230 StringBuffer sb = new StringBuffer(); 231 int len = source.length; 232 int i = 0; 233 int b1, b2, b3; 234 while (i < len) { 235 b1 = source[i++] & 0xff; 236 if (i == len) { 237 sb.append(base64EncodeChars[b1 >>> 2]); 238 sb.append(base64EncodeChars[(b1 & 0x3) << 4]); 239 sb.append("=="); 240 break; 241 } 242 b2 = source[i++] & 0xff; 243 if (i == len) { 244 sb.append(base64EncodeChars[b1 >>> 2]); 245 sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); 246 sb.append(base64EncodeChars[(b2 & 0x0f) << 2]); 247 sb.append("="); 248 break; 249 } 250 b3 = source[i++] & 0xff; 251 sb.append(base64EncodeChars[b1 >>> 2]); 252 sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); 253 sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]); 254 sb.append(base64EncodeChars[b3 & 0x3f]); 255 } 256 return sb.toString(); 257 } catch (Exception e) { 258 LogUtils.e("base64_encode(): error=" + e.getMessage(), "StringTool"); 259 return ""; 260 } 261 } 262 263 /** 264 * base64编码,解码为字节数组 265 * 266 * @param source 267 * @return byte[] 268 */ 269 public static byte[] base64_decode(String source) { 270 byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 }; 271 try { 272 byte[] data = source.getBytes(); 273 int len = data.length; 274 ByteArrayOutputStream buf = new ByteArrayOutputStream(len); 275 int i = 0; 276 int b1, b2, b3, b4; 277 while (i < len) { 278 /* b1 */ 279 do { 280 b1 = base64DecodeChars[data[i++]]; 281 } while (i < len && b1 == -1); 282 if (b1 == -1) 283 break; 284 285 /* b2 */ 286 do { 287 b2 = base64DecodeChars[data[i++]]; 288 } while (i < len && b2 == -1); 289 if (b2 == -1) 290 break; 291 buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4))); 292 293 /* b3 */ 294 do { 295 b3 = data[i++]; 296 if (b3 == 61) 297 return buf.toByteArray(); 298 b3 = base64DecodeChars[b3]; 299 } while (i < len && b3 == -1); 300 if (b3 == -1) 301 break; 302 buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); 303 304 /* b4 */ 305 do { 306 b4 = data[i++]; 307 if (b4 == 61) 308 return buf.toByteArray(); 309 b4 = base64DecodeChars[b4]; 310 } while (i < len && b4 == -1); 311 if (b4 == -1) 312 break; 313 buf.write((int) (((b3 & 0x03) << 6) | b4)); 314 } 315 return buf.toByteArray(); 316 } catch (Exception e) { 317 LogUtils.i("ls", "base64_decode(): error=" + e.getMessage()); 318 return "".getBytes(); 319 } 320 } 321 322 public static String join(String separator, Object[] o) { 323 return implode(separator, Arrays.asList(o)); 324 } 325 326 protected static <T> String implode(String separator, Iterable<T> elements) { 327 StringBuilder out = new StringBuilder(); 328 boolean first = true; 329 for (Object s : elements) { 330 if (s == null) 331 continue; 332 else if (first) 333 first = false; 334 else 335 out.append(separator); 336 out.append(s); 337 } 338 return out.toString(); 339 } 340 341 public static String[] explode(String glue, String str) { 342 String[] outData; 343 try { 344 StringTokenizer st = new StringTokenizer(str, glue); 345 outData = new String[st.countTokens()]; 346 for (int i = 0; st.hasMoreTokens();) { 347 outData[i++] = st.nextToken(); 348 } 349 } catch (Exception e) { 350 outData = new String[] { str }; 351 e.printStackTrace(); 352 } 353 return outData; 354 } 355 356 /** 357 * 得到字符串双字节长度 358 * 359 * @param str 360 * @return 361 */ 362 public static int getDoubleByteLength(String str) { 363 return str.replaceAll("[^\\x00-\\xff]", "xx").trim().length(); 364 } 365 366 /** 367 * 将流转换成字符串 368 * 369 * @param is 370 * @return 371 */ 372 public static String getStringByStream(InputStream is) { 373 StringBuffer sb = new StringBuffer(); 374 try { 375 BufferedReader br = new BufferedReader(new InputStreamReader(is)); 376 String line = null; 377 while ((line = br.readLine()) != null) { 378 sb.append(line); 379 } 380 } catch (Exception e) { 381 e.printStackTrace(); 382 } 383 return sb.toString(); 384 } 385 386 /** 387 * 将流转换成字符串 388 * 389 * @param is 390 * @param chatset 391 * 字符编码 392 * @return 393 */ 394 public static String getStringByStream(InputStream is, String chatset) { 395 StringBuffer sb = new StringBuffer(); 396 try { 397 byte[] bytes = new byte[1024]; 398 int len = 0; 399 while ((len = is.read(bytes)) != -1) { 400 sb.append(new String(bytes, 0, len, chatset)); 401 } 402 } catch (Exception e) { 403 // TODO: handle exception 404 e.printStackTrace(); 405 } 406 return sb.toString(); 407 } 408 409 }
以上是关于android开发字符串工具类的主要内容,如果未能解决你的问题,请参考以下文章