String工具类--持续更新
常用方法:
1、boolean isEmpty(String str):判断字符串是否为空
2、String转换为Integer、Long、Double、BigDecimal等
3、boolean stringEquals(String str1, String str2):比较两个字符串是否相等
4、String replaceAllBlank(String s):去除字符串间的空格
5、String replaceAll(String source, String oldString, String newString):字符串替换,将 source 中的 oldString 全部换成 newString
6、boolean checkEmail(String emailStr):检测是否为合法的E-MAIL格式
7、String encryptMD5(String value):将字符串进行MD5加密,空字符串直接返回""
8、int occurTimes(String string, String substr):统计字符串中指定字符串出现的字数
工具类代码如下:
1 import java.math.BigDecimal;
2 import java.security.MessageDigest;
3 import java.text.DecimalFormat;
4 import java.text.NumberFormat;
5 import java.util.ArrayList;
6 import java.util.Collection;
7 import java.util.Date;
8 import java.util.HashMap;
9 import java.util.HashSet;
10 import java.util.Iterator;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.Set;
14 import java.util.Vector;
15
16 import org.springframework.util.StringUtils;
17
18 /**
19 *
20 * <p>
21 * Title: StringUtil.java
22 * </p>
23 * <p>
24 * Description: 对字符串的类型转化或处理相关的操作
25 * @version 1.0
26 *
27 */
28 @SuppressWarnings({ "unchecked", "rawtypes" })
29 public class StringUtil {
30
31 private static final String DEFAULT_FILTERED_CHAR = "`~\\:;\"'<,>./";
32
33 // private static final String[] DEFAULT_INVALID_STR = new
34 // String[]{"'","script","and ","or ","union ","between
35 // ","\"","\\","=","\\t","insert|values","select|from","update|set","delete|from","drop","where","alter"};
36 // private static final String[] DEFAULT_INVALID_STR = new
37 // String[]{"'","script","and ","or ","union ","between
38 // ","\"","\\","\\t","insert|values","select|from","update|set","delete|from","drop","where","alter"};
39 private static final String[] DEFAULT_INVALID_STR = new String[] { "script", "and ", "or ", "union ", "between ", "\"", "\\", "\\t", "insert|values", "select|from", "update|set", "delete|from", "drop", "where", "alter" };
40
41 /**
42 * 判断字符串是否为空
43 *
44 * @param str
45 * @return boolean
46 *
47 */
48 public static boolean isEmpty(Object str) {
49 return (str == null || (String.valueOf(str)).trim().length() < 1);
50 }
51
52 /**
53 * 判断字符串是否为非空
54 *
55 * @param str
56 * @return boolean
57 *
58 */
59 public static boolean isNotEmpty(Object str) {
60 return !isEmpty(str);
61 }
62
63 /**
64 * 判断字符串是否为空
65 *
66 * @param str
67 * @return boolean
68 *
69 */
70 public static boolean isEmpty(String str) {
71 return (str == null || str.trim().length() < 1);
72 }
73
74 /**
75 * 判断字符串是否为非空
76 *
77 * @param str
78 * @return boolean
79 *
80 */
81 public static boolean isNotEmpty(String str) {
82 return !isEmpty(str);
83 }
84
85 /**
86 * Object转化为字符串
87 *
88 * @param obj
89 * @return String
90 *
91 */
92 public static String obj2Str(Object obj) {
93 return obj == null ? "" : obj.toString().trim();
94 }
95
96 /**
97 * Object转化为字符串,设置默认值,如果为空返回默认值
98 *
99 * @param obj
100 * 对象
101 * @param defaultValue
102 * 默认值
103 * @return String
104 *
105 */
106 public static String obj2Str(Object obj, String defaultValue) {
107 return obj == null ? defaultValue : obj.toString().trim();
108 }
109
110 /**
111 * 字符串转化为Integer类型
112 *
113 * @param str
114 * @return Integer
115 *
116 */
117 public static Integer string2Integer(String str) {
118 if (isNotEmpty(str)) {
119 try {
120 return new Integer(str.trim());
121 } catch (NumberFormatException e) {
122 e.printStackTrace();
123 }
124 }
125 return null;
126 }
127
128 /**
129 * 字符串转化为Integer类型,为空则返回默认值
130 *
131 * @param str
132 * @param defaultValue
133 * 默认值
134 * @return Integer
135 *
136 */
137 public static Integer string2Integer(String str, Integer defaultValue) {
138 if (isNotEmpty(str)) {
139 try {
140 return new Integer(str.trim());
141 } catch (NumberFormatException e) {
142 e.printStackTrace();
143 return defaultValue;
144 }
145 }
146 return defaultValue;
147 }
148
149 /**
150 * 字符串转化为Long类型
151 *
152 * @param str
153 * @return Long
154 *
155 */
156 public static Long string2Long(String str) {
157 if (isNotEmpty(str)) {
158 try {
159 return new Long(str.trim());
160 } catch (NumberFormatException e) {
161 e.printStackTrace();
162 }
163 }
164 return null;
165 }
166
167 /**
168 *
169 * 字符串转化为Long类型,为空则返回默认值
170 *
171 * @param str
172 * @param defaultValue
173 * 默认值
174 * @return Long
175 *
176 */
177 public static Long string2Long(String str, Long defaultValue) {
178 if (isNotEmpty(str)) {
179 try {
180 return new Long(str.trim());
181 } catch (NumberFormatException e) {
182 e.printStackTrace();
183 return defaultValue;
184 }
185 }
186 return defaultValue;
187 }
188
189 /**
190 * 字符串转化为Double类型
191 *
192 * @param str
193 * @return Double
194 *
195 */
196 public static Double stringToDouble(String str) {
197 if (isNotEmpty(str)) {
198 try {
199 return new Double(str.trim());
200 } catch (NumberFormatException e) {
201 e.printStackTrace();
202 }
203 }
204 return null;
205 }
206
207 /**
208 *
209 * 字符串转化为Double类型,为空则返回默认值
210 *
211 * @param str
212 * @param defaultValue
213 * 默认值
214 * @return Double
215 *
216 */
217 public static Double stringToDouble(String str, Double defaultValue) {
218 if (isNotEmpty(str)) {
219 try {
220 return new Double(str.trim());
221 } catch (NumberFormatException e) {
222 e.printStackTrace();
223 return defaultValue;
224 }
225 }
226 return defaultValue;
227 }
228
229 /**
230 * 字符串转化为BigDecimal类型
231 *
232 * @param str
233 * @return BigDecimal
234 *
235 */
236 public static BigDecimal string2BigDecimal(String str) {
237 if (isNotEmpty(str)) {
238 try {
239 return new BigDecimal(str);
240 } catch (NumberFormatException e) {
241 e.printStackTrace();
242 }
243 }
244 return null;
245 }
246
247 /**
248 *
249 * 字符串转化为BigDecimal类型,为空则返回默认值
250 *
251 * @param str
252 * @param defaultValue
253 * 默认值
254 * @return BigDecimal
255 *
256 */
257 public static BigDecimal string2BigDecimal(String str, BigDecimal defaultValue) {
258 if (isNotEmpty(str)) {
259 try {
260 return new BigDecimal(str);
261 } catch (NumberFormatException e) {
262 e.printStackTrace();
263 return defaultValue;
264 }
265 }
266 return defaultValue;
267 }
268
269 /**
270 * 判断字符串是否为数字
271 *
272 * @param str
273 * @return boolean
274 *
275 */
276 public static boolean isDecimal(String str) {
277 boolean res = true;
278 if (isEmpty(str)) {
279 return false;
280 }
281 try {
282 new BigDecimal(str);
283 } catch (NumberFormatException e) {
284 res = false;
285 }
286 return res;
287 }
288
289 /**
290 *
291 * 将字符串格式化为数字形式的字符串
292 *
293 * @param value
294 * 初始字符串
295 * @return String 数字形式的字符串
296 *
297 */
298 public static String numberFormat(String value) {
299 if (!isEmpty(value)) {
300 NumberFormat format = NumberFormat.getInstance();
301 return format.format(Double.parseDouble(value));
302 }
303 return null;
304 }
305
306 /**
307 * 判断是否是中文字符,判断中文的"“"、"。"、","号
308 *
309 * @param c
310 * @return boolean
311 *
312 */
313 // GENERAL_PUNCTUATION 判断中文的“号
314 // CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号
315 // HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的,号
316 public static boolean isChinese(char c) {
317 Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
318 if ((ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) || (ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS) || (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A) || (ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) || (ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION) || (ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS)) {
319 return true;
320 }
321 return false;
322 }
323
324 /**
325 * 判断是否是中文字符串
326 *
327 * @param str
328 * @return boolean
329 *
330 */
331 public static boolean isChinese(String str) {
332 if (isEmpty(str)) {
333 return false;
334 }
335 char[] ch = str.toCharArray();
336 for (int i = 0; i < ch.length; i++) {
337 char c = ch[i];
338 if (isChinese(c) == true) {
339 return true;
340 }
341 }
342 return false;
343 }
344
345 /**
346 * 比较两个字符串是否相等
347 *
348 * @param str1
349 * @param str2
350 * @return boolean
351 *
352 */
353 public static boolean stringEquals(String str1, String str2) {
354 if (isEmpty(str1) && isEmpty(str2)) {
355 return true;
356 }
357 // str1不等于null
358 if (isNotEmpty(str1)) {
359 return str1.equals(str2);
360 }
361 // str2肯定不为null
362 return false;
363 }
364
365 /**
366 *
367 * 将对象数组(toString方法)转换成用逗号分割的字符串
368 *
369 * @param strArray
370 * 对象数组
371 * @return 以逗号分隔的字符串
372 *
373 */
374 public static String array2Str(Object[] strArray) {
375 String str = "";
376 for (int i = 0; i < strArray.length; i++) {
377 str += strArray[i].toString() + ",";
378 }
379 if (str.length() > 0)
380 str = str.substring(0, str.length() - 1);
381 return str;
382 }
383
384 /**
385 * 将逗号分割的字符串转换成字符串数组
386 *
387 * @param str
388 * 以逗号分隔的字符串
389 * @return 字符串数组
390 */
391 public static String[] str2Array(String str) {
392 Vector vect = (Vector) getVector(str, ",");
393 int num = vect.size();
394 String strArray[] = new String[num];
395 for (int i = 0; i < num; i++) {
396 strArray[i] = (String) vect.elementAt(i);
397 }
398 return strArray;
399 }
400
401 /**
402 * 将split指定分隔符分隔的字符,转换成set
403 *
404 * @return
405 */
406 public static Set commaString2Set(String commaString, String split) {
407 Set s = new HashSet();
408 if (isNotEmpty(commaString)) {
409 String[] arr = commaString.split(split);
410 for (int i = 0; i < arr.length; i++) {
411 s.add(arr[i].trim());
412 }
413 }
414 return s;
415 }
416
417 /**
418 * 将split指定分隔符分隔的字符,转换成set,默认用","分隔
419 *
420 * @return
421 */
422 public static Set commaString2Set(String commaString) {
423 return commaString2Set(commaString, ",");
424 }
425
426 /**
427 * 将'1232','234','234'或者1232,234,234类型的字符串转化为list
428 *
429 * @param str
430 * '1232','234','234'或者1232,234,234类型的字符串,","为分隔符
431 * @param splitStr
432 * 分隔符,如","
433 * @param removeComma
434 * 是否移除单引号"'",如果有则设置为true,没有设置为false
435 * @return List<String>
436 *
437 */
438 public static List<String> string2List(String str, String splitStr, boolean removeComma) {
439 List<String> list = new ArrayList<String>();
440 int pos = str.indexOf(splitStr);
441 boolean hasSplit = false;
442 if (pos >= 0) {
443 hasSplit = true;
444 }
445 while (pos >= 0) {
446 String obj = str.substring(0, pos);
447 if (removeComma) {
448 obj = obj.substring(1, obj.length() - 1);
449 }
450 list.add(obj);
451 str = str.substring(pos + 1, str.length());
452 pos = str.indexOf(splitStr);
453 }
454 if (hasSplit) {
455 if (removeComma) {
456 str = str.substring(1, str.length() - 1);
457 }
458 list.add(str);
459 }
460 return list;
461 }
462
463 /**
464 *
465 * 判断字符串target是否在指定的字符之间 不区分大小写 比如判断"from"是否在"()"之中 对于语句:select count(*)
466 * from table where (1=1); return false 对于语句:(select count(*) from table
467 * where (1=1)); return true 对于语句:select * from table; return true
468 *
469 * @param str
470 * @param target
471 * @param pos
472 * target所在字符串str的位置,如果设置错误会抛异常
473 * @param begin
474 * @param end
475 * @return
476 * @throws Exception
477 * boolean
478 *
479 */
480 public static boolean contains(String str, String target, int pos, char begin, char end) throws Exception {
481 int b = str.indexOf(begin);
482 int e = str.indexOf(end);
483 if ((b < 0) || (e < 0)) {
484 return false;
485 }
486
487 int len = target.length();
488 System.out.println(str.length() + ":" + pos + ":" + len);
489 String s = str.substring(pos, pos + len);
490 if (!s.equalsIgnoreCase(target)) {
491 throw new Exception("string['" + target + "]location:[" + pos + "]Unspecified error");
492 }
493
494 String frontStr = str.substring(0, pos);
495 String backStr = str.substring(pos + len + 1);
496 // System.out.println("frontStr=["+frontStr+"],backStr=["+backStr+"]");
497
498 int endCount = 0;
499 int beginCount = 0;
500 // 判断是否存在不匹对的begin字符
501 boolean existBegin = false;
502 for (int i = 0; i < frontStr.length(); i++) {
503 char c = frontStr.charAt(i);
504 if (c == begin) {
505 beginCount++;
506 }
507 if (c == end) {
508 endCount++;
509 }
510 }
511 if ((beginCount - endCount) > 0) {
512 existBegin = true;
513 }
514
515 endCount = 0;
516 beginCount = 0;
517 // 判断是否存在不匹对的end字符
518 boolean existEnd = false;
519 for (int i = 0; i < backStr.length(); i++) {
520 char c = backStr.charAt(i);
521 if (c == begin) {
522 beginCount++;
523 }
524 if (c == end) {
525 endCount++;
526 }
527 }
528 if ((endCount - beginCount) > 0) {
529 existEnd = true;
530 }
531 return existBegin && existEnd;
532 }
533
534 /**
535 * 在str中查找不在begin和end之间的target的位置 比如,在sql中找不在括号内的from关键字的位置 不区分大小写
536 *
537 * @param str
538 * @param target
539 * @param begin
540 * @param end
541 * @return
542 * @throws Exception
543 */
544 public static int getPosNotIn(String str, String target, char begin, char end) throws Exception {
545 String opStr = str;
546 int pos = 0;// 在opStr中的位置
547 int modify = 0;// str4和opStr长度差值
548 boolean inIf = false;
549 while (opStr.toLowerCase().indexOf(target.toLowerCase()) >= 0) {
550 System.out.println("opStr=[" + opStr + "]");
551 pos = opStr.toLowerCase().indexOf(target.toLowerCase());
552 if (!contains(str, target, pos + modify, begin, end)) {
553 inIf = true;
554 break;
555 }
556 opStr = opStr.substring(pos + target.length());
557 modify += pos + target.length();
558 System.out.println("modify=" + modify);
559 }
560
561 if (!inIf) {
562 return -1;
563 } else {
564 pos = modify + pos;
565 System.out.println(str.substring(pos, pos + target.length()) + " found,pos=[" + pos + "],modify=[" + modify + "]");
566 return pos;
567 }
568 }
569
570 /**
571 *
572 * 去除字符串间的空格
573 *
574 * @param s
575 * @return String
576 *
577 */
578 public static String replaceAllBlank(String s) {
579 if (isEmpty(s)) {
580 return "";
581 }
582 return s.replaceAll("\\s", "");
583 }
584
585 /**
586 * 字符串替换,将 source 中的 oldString 全部换成 newString
587 *
588 * @param source
589 * 源字符串
590 * @param oldString
591 * 老的字符串
592 * @param newString
593 * 新的字符串
594 * @return 替换后的字符串
595 */
596 public static String replaceAll(String source, String oldString, String newString) {
597 if ((source == null) || (source.equals(""))) {
598 return "";
599 }
600 StringBuffer output = new StringBuffer();
601
602 int lengthOfSource = source.length(); // 源字符串长度
603 int lengthOfOld = oldString.length(); // 老字符串长度
604
605 int posStart = 0; // 开始搜索位置
606 int pos; // 搜索到老字符串的位置
607
608 while ((pos = source.indexOf(oldString, posStart)) >= 0) {
609 output.append(source.substring(posStart, pos));
610
611 output.append(newString);
612 posStart = pos + lengthOfOld;
613 }
614
615 if (posStart < lengthOfSource) {
616 output.append(source.substring(posStart));
617 }
618
619 return output.toString();
620 }
621
622 /**
623 * 将字符串数组转化为以逗号分隔的字符串
624 *
625 * @param s
626 * @return String 逗号分隔的字符串
627 *
628 */
629 public static String arr2CommaString(String[] s) {
630 if (s == null || s.length < 1) {
631 return "";
632 }
633 String result = s[0];
634 if (s.length > 1) {
635 for (int i = 1; i < s.length; i++) {
636 result += ("," + s[i]);
637 }
638 }
639 return result;
640 }
641
642 /**
643 * 构造字符串,将列表中的字符串,用分隔符连成一个字符串
644 *
645 * @param list
646 * List 字符串(String)列表
647 * @param splitStr
648 * String 分隔符
649 * @return String
650 */
651 public static String list2StringWithSplit(List list, String splitStr) {
652 if (list == null || list.size() < 1)
653 return null;
654
655 StringBuffer buf = new StringBuffer();
656 Iterator iter = list.iterator();
657 while (iter.hasNext()) {
658 buf.append(splitStr);
659 buf.append((String) iter.next());
660 }
661 return buf.toString().substring(1);
662 }
663
664 /**
665 *
666 * 构造字符串,将列表中的字符串,连成一个字符串
667 *
668 * @param list
669 * @return
670 */
671 public static String list2String(List list) {
672 if (list == null || list.size() <= 0)
673 return null;
674
675 StringBuffer buf = new StringBuffer();
676 Iterator iter = list.iterator();
677 while (iter.hasNext()) {
678 buf.append((String) iter.next());
679 }
680 return buf.toString();
681 }
682
683 /**
684 * 构造字符串,将列表中的字符串,用分隔符连成一个字符串 每个字符串加上单引号 查询DATABASE用
685 *
686 * @param list
687 * Collection
688 * @param splitStr
689 * String
690 * @return String
691 */
692 public static String list2StringWithComma(Collection list, String splitStr) {
693 if (list == null || list.size() < 1)
694 return null;
695
696 StringBuffer buf = new StringBuffer();
697 Iterator iter = list.iterator();
698 while (iter.hasNext()) {
699 buf.append(splitStr);
700 buf.append("'");
701 buf.append((String) iter.next());
702 buf.append("'");
703 }
704
705 return buf.toString().substring(1);
706 }
707
708 /**
709 * 删除某个字串中需要被过滤的字符
710 *
711 * @param src
712 * @param filterChar
713 * @return
714 */
715 public static String filterStr(String src, String filterChar) {
716 if (isEmpty(src))
717 return "";
718 src = src.trim();
719 if (filterChar == null || filterChar.length() < 0) {
720 filterChar = DEFAULT_FILTERED_CHAR;
721 }
722 int len = filterChar.length();
723 for (int i = 0; i < len; i++) {
724 src = src.replaceAll("\\" + String.valueOf(filterChar.charAt(i)), "");
725 }
726 return src;
727 }
728
729 /**
730 * 判断字串中是否包含非法字串 added by wwl 2007-6-15
731 *
732 * @param src
733 * @param invalidStr
734 * @return
735 */
736 public static boolean isContainInvalidStr(String src, String invalidStr) {
737 boolean res = false;
738 if (isEmpty(src)) {
739 return res;
740 }
741 // 使用自定义非法字串进行检查
742 if (invalidStr != null && invalidStr.length() > 0) {
743 res = (src.indexOf(invalidStr) >= 0) ? true : false;
744 }
745 // 使用系统内置非法字串进行检查
746 else {
747 int len = DEFAULT_INVALID_STR.length;
748 src = src.toLowerCase();
749 String tmpInvalidStr;
750 String[] tmpArr;
751 boolean tmpBol;
752 for (int i = 0; i < len; i++) {
753 tmpInvalidStr = DEFAULT_INVALID_STR[i];
754 // System.out.println(i + "." + tmpInvalidStr);
755 // 多个关联非法字串
756 if (tmpInvalidStr.indexOf("|") >= 0) {
757 tmpBol = false;
758 tmpArr = tmpInvalidStr.split("[|]");
759 for (int j = 0; j < tmpArr.length; j++) {
760 // System.out.println(i + "." + j + " " + tmpArr[j]);
761 // 每个关联非法字串都在源字串中,才能判断整个源字串是非法的
762 if (src.indexOf(tmpArr[j]) >= 0) {
763 System.out.println("invalid str [" + tmpArr[j] + "] exist,");
764 tmpBol = true;
765 }
766 // 有一个关联非法字串不在源字串中,源字串就是合法的
767 else {
768 tmpBol = false;
769 break;
770 }
771 }
772 if (tmpBol) {
773 res = true;
774 break;
775 }
776 }
777 // 单个非法字串
778 else {
779 if (src.indexOf(tmpInvalidStr) >= 0) {
780 System.out.println("invalid str [" + tmpInvalidStr + "] exist, quit");
781 res = true;
782 break;
783 }
784 }
785 }
786 }
787
788 return res;
789 }
790
791 /**
792 * 将字符串中的单引号"'"改为两个单引号"''",用于数据库操作
793 *
794 * @param str
795 * String
796 * @return String
797 */
798 public static String convertComma2Db(String str) {
799 int pos = str.indexOf("'");
800 int pos1 = 0;
801 while (pos != -1) {
802 str = str.substring(0, pos1 + pos) + "'" + str.substring(pos + pos1, str.length());
803 pos1 = pos1 + pos + 2;
804 pos = str.substring(pos1, str.length()).indexOf("'");
805 }
806 return str;
807 }
808
809 /**
810 * 把型如"12,23,34,56"的字串转换为"'12','23','34','56'"能在SQL中使用的字串
811 *
812 * @param source
813 * String
814 * @return String
815 */
816 public static String addInvertedComma(String source) {
817 if (isEmpty(source))
818 return null;
819 source = "'" + source.trim();
820 int pos = source.indexOf(",");
821 int len = source.length();
822 while (pos != -1) {
823 source = source.substring(0, pos) + "','" + source.substring(pos + 1, len);
824 len += 2;
825 pos += 2;
826 if (source.substring(pos).indexOf(",") != -1)
827 pos = source.substring(pos).indexOf(",") + pos;
828 else
829 break;
830 }
831 source += "'";
832 return source;
833 }
834
835 /**
836 *
837 * 按起始、终止字符将字符串分段,每段中的字符串以分隔符分割, 保存到vector,再将每段得到的vector存放到结果vector返回。<br />
838 * 如字符串"[123;456][789;012]<br />
839 * 先按起始、终止字符分成[123;456]和[789;012]两段<br />
840 * 然后以";"分别分割两段字符串,得到的结果"123","456"放到一个vector对象v1,"789","012"放到一个vector对象v2
841 * <br />
842 * 最后将v1、v2放到最后的返回结果vector中
843 *
844 * @param str
845 * @param beginStr
846 * 起始字符串
847 * @param endStr
848 * 终止字符串
849 * @param splitStr
850 * 分段字符串中的分隔符
851 * @return Vector
852 *
853 */
854 public static Vector<Vector<String>> getVectorBySegment(String str, String beginStr, String endStr, String splitStr) {
855 Vector<Vector<String>> vect = new Vector<Vector<String>>();
856 String strTemp = "";
857 int bpos = str.indexOf(beginStr);
858 int epos = str.indexOf(endStr);
859 while (bpos >= 0 && epos > 0) {
860 strTemp = str.substring(bpos + 1, epos);
861 Vector<String> subvect = getVector(strTemp, splitStr);
862 vect.addElement(subvect);
863 str = str.substring(epos + 1, str.length());
864 bpos = str.indexOf(beginStr);
865 epos = str.indexOf(endStr);
866 }
867 return vect;
868 }
869 /**
870 * 将一个字符串按照指定的分割符进行分割
871 *
872 * @param str
873 * String
874 * @param splitStr
875 * String
876 * @return Vector
877 */
878 public static Vector<String> getVector(String str, String splitStr) {
879 Vector<String> vect = new Vector<String>();
880 int pos = str.indexOf(splitStr);
881 int len = splitStr.length();
882 while (pos >= 0) {
883 vect.addElement(str.substring(0, pos));
884 str = str.substring(pos + len, str.length());// huangc modify
885 pos = str.indexOf(splitStr);
886 }
887 vect.addElement(str.substring(0, str.length()));
888 return vect;
889 }
890
891
892 /**
893 *
894 * 为一个字符串的左边添加字符串strspace,以满足strlen要求修改后的长度
895 *
896 * @param str
897 * @param strspace
898 * 左边添加的字符
899 * @param strlen
900 * 要求长度
901 * @return String
902 *
903 */
904 public static String addChar4Len(String str, String strspace, int strlen) {
905 if (str == null || str.length() < 1 || strspace == null || strspace.length() < 1)
906 return str;
907 while (str.length() < strlen) {
908 if (str.length() + strspace.length() > strlen) {
909 return str;
910 }
911 str = strspace + str;
912 }
913 return str;
914 }
915
916 /**
917 * 将字符串的集合转换成用指定分隔符分割的字符串,addComma参数是指定字符串是否添加单引号
918 *
919 * @param collection
920 * @param separator
921 * 分隔符,为空是默认为逗号
922 * @param addComma
923 * 指定字符串是否添加单引号
924 * @return String
925 *
926 */
927 public static String list2String(Collection collection, String separator, boolean addComma) {
928 String str = "";
929 if (null == collection || collection.size() < 1) {
930 return str;
931 }
932 if (null == separator || separator.length() < 1) {
933 separator = ",";
934 }
935 Iterator it = collection.iterator();
936 while (it.hasNext()) {
937 str += (addComma ? "'" : "") + obj2Str(it.next(), "") + (addComma ? "'" : "") + separator;
938 }
939 if (str.length() > 0) {
940 str = str.substring(0, str.length() - 1);
941 }
942 return str;
943 }
944
945 /**
946 *
947 * 将多个list中的数据合并,剔除重复的数据
948 *
949 * @param lists
950 * @return List
951 *
952 */
953 public static List<Object> getDistinctList(List[] lists) {
954 List<Object> retList = new ArrayList<Object>();
955 Map<Object, Object> map = new HashMap<Object, Object>();
956 for (int i = 0; i < lists.length; i++) {
957 List<Object> list = (List) lists[i];
958 if (list == null) {
959 continue;
960 }
961 for (int j = 0; j < list.size(); j++) {
962 if (list.get(j) != null) {
963 map.put(list.get(j), list.get(j));
964 }
965 }
966 }
967 Iterator<Object> it = map.keySet().iterator();
968 while (it.hasNext()) {
969 retList.add(it.next());
970 }
971 return retList;
972 }
973
974
975 /**
976 *
977 * 根据身份证号码获取性别(返回值:1-男,2-女,空为身份证号码错误)
978 *
979 * @param iDCard
980 * 身份证号
981 * @return String 返回值:1-男,2-女,空为身份证号码错误
982 *
983 */
984 public static String getGender(String iDCard) {
985 int gender = 3;
986 if (iDCard.length() == 15) {
987 gender = (new Integer(iDCard.substring(14, 15))).intValue() % 2;
988 } else if (iDCard.length() == 18) {
989 int number17 = (new Integer(iDCard.substring(16, 17))).intValue();
990 gender = number17 % 2;
991 }
992 if (gender == 1) {
993 return "1";
994 } else if (gender == 0) {
995 return "2";
996 } else {
997 return "";
998 }
999 }
1000
1001 /**
1002 * 检测是否为合法的E-MAIL格式
1003 *
1004 * @param emailStr
1005 * @return boolean
1006 *
1007 */
1008 public static boolean checkEmail(String emailStr) {
1009 if (isEmpty(emailStr)) {
1010 return false;
1011 }
1012 return emailStr.matches("[-_.a-zA-Z0-9]+@[-_a-zA-Z0-9]+.[a-zA-Z]+");
1013 }
1014
1015 /**
1016 * 检测是否是字母,数字,下划线
1017 *
1018 * @param v
1019 * @return boolean
1020 *
1021 */
1022 public static boolean checkStr(String v) {
1023 if (isEmpty(v)) {
1024 return false;
1025 }
1026 return v.matches("[a-zA-Z0-9_]*");
1027 }
1028
1029 /**
1030 * 将字符串进行MD5加密,空字符串直接返回""
1031 *
1032 * @param value
1033 * @return
1034 * @throws Exception
1035 * String 加密后的字符串
1036 *
1037 */
1038 public static String encryptMD5(String value) throws Exception {
1039 String result = "";
1040 if (isEmpty(value)) {
1041 return "";
1042 }
1043 try {
1044 MessageDigest messageDigest = MessageDigest.getInstance("MD5");
1045 messageDigest.update(value.getBytes());
1046 result = byte2hex(messageDigest.digest());
1047 } catch (Exception e) {
1048 e.printStackTrace();
1049 throw new Exception(e.getMessage());
1050 }
1051 return result;
1052 }
1053
1054 private static String byte2hex(byte[] bytes) {
1055 String result = "";
1056 String stmp = "";
1057 for (int n = 0; n < bytes.length; n++) {
1058 stmp = (java.lang.Integer.toHexString(bytes[n] & 0xFF));
1059 if (stmp.length() == 1) {
1060 result = result + "0" + stmp;
1061 } else {
1062 result = result + stmp;
1063 }
1064 }
1065 return result.toUpperCase();
1066 }
1067
1068 /**
1069 *
1070 * 统计字符串中指定字符串出现的字数
1071 *
1072 * @param string
1073 * 原字符串
1074 * @param substr
1075 * 需要统计的字符串
1076 * @return
1077 */
1078 public static int occurTimes(String string, String substr) {
1079 int pos = -2;
1080 int n = 0;
1081
1082 while (pos != -1) {
1083 if (pos == -2) {
1084 pos = -1;
1085 }
1086 pos = string.indexOf(substr, pos + 1);
1087 if (pos != -1) {
1088 n++;
1089 }
1090 }
1091 return n;
1092 }
1093
1094 public static void main(String[] args) {
1095 String testStr = "aa;bb;cc|dd;ee;ff";
1096 Vector v = StringUtil.getVector(testStr, "|");
1097 for (int i = 0; i < v.size(); i++) {
1098 System.out.println(v.get(i));
1099 }
1100
1101 String strPath = "file:/crmtest/product/suite400/webapp/WEB-INF/lib/aibi-waterMark-1.2.0-SNAPSHOT.jar!/META-INF/MANIFEST.MF";
1102 strPath = strPath.substring(5, strPath.indexOf("!"));
1103 System.out.println(strPath);
1104 strPath = strPath.substring(0, strPath.lastIndexOf("/") + 1);
1105 System.out.println(strPath);
1106 System.out.println(getGender("340122199003046913"));
1107 formatString("", "");
1108
1109 System.out.println(occurTimes("sdfdsfsdfsdf", "sd") + " 888888888888888888888");
1110 }
1111 }