首页 > 代码库 > 操作字符串的工具类

操作字符串的工具类

  1 package com.sunyard.util;
  2 
  3 import java.io.IOException;
  4 import java.io.UnsupportedEncodingException;
  5 import java.sql.Blob;
  6 import java.sql.Clob;
  7 import java.text.DateFormat;
  8 import java.text.SimpleDateFormat;
  9 import java.util.Arrays;
 10 import java.util.Date;
 11 import java.util.List;
 12 import java.util.TimeZone;
 13 import java.util.regex.Matcher;
 14 import java.util.regex.Pattern;
 15 
 16 import net.sourceforge.pinyin4j.PinyinHelper;
 17 import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
 18 import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
 19 import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
 20 import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
 21 
 22 import org.apache.commons.lang3.ArrayUtils;
 23 import org.apache.commons.lang3.StringUtils;
 24 
 25 /**
 26  * <p>字符串工具类</p>
 27  */
 28 public class StrUtil {
 29     /**
 30      * 功能:格式化空字符串
 31      * 
 32      * @param str
 33      * @return String
 34      */
 35     public static String formatNull(String str) {
 36         return null == str || "null".equals(str) ? "" : str;
 37     }
 38 
 39     /**
 40      * 功能:格式化空字符串,为空时返回默认字符串
 41      * 
 42      * @param str            原字符串
 43      * @param defaultStr    默认字符串
 44      * @return String
 45      */
 46     public static String formatNull(String str,String defaultStr) {
 47         return StrUtil.isNull(str) ? defaultStr : str;
 48     }
 49 
 50     /**
 51      * 功能:判断字符串是否为空
 52      * 
 53      * @param str
 54      * @return boolean
 55      */
 56     public static boolean isNull(String str) {
 57         return null == str || "".equals(str) || "null".equals(str);
 58     }
 59 
 60     /**
 61      * 将String转换成byte数组
 62      * 
 63      * @param in
 64      * @return String
 65      */
 66     public static byte[] stringToByte(String str,String encoding) {
 67         byte[] result = null;
 68         try {
 69             encoding = StrUtil.isNull(encoding) ? "GBK" : encoding;
 70             result = str.getBytes(encoding);
 71         } catch (UnsupportedEncodingException e) {
 72             e.printStackTrace();
 73         }
 74         return result;
 75     }
 76     
 77     /**
 78      * 为字符串后面不足补a
 79      * 
 80      * @param str
 81      *            需要处理的字符串
 82      * @param length
 83      *            补零后的总长度
 84      * @param type
 85      *            类型:1.往前补a 2.往后补a
 86      * @param chars
 87      *            类型:字符
 88      * @return 长度为length的补零后的字符串
 89      */
 90     public static String fillChar(String str, int length, int type,String chars) {
 91         String code = "";
 92         for (int i = 0; i < length; i++) {
 93             code = code + chars;
 94         }
 95 
 96         if (type == 1) {
 97             code = code.substring(str.length()) + str;
 98         } else {
 99             code = str + code.substring(str.length());
100         }
101         return code;
102     }
103 
104 
105     /**
106      * 将byte数组转换成String
107      * 
108      * @param in
109      * @return String
110      */
111     public static String byteToString(byte[] bytes,String encoding) {
112         String result = null;
113         try {
114             encoding = StrUtil.isNull(encoding) ? "GBK" : encoding;
115             result = new String(bytes, encoding);
116         } catch (UnsupportedEncodingException e) {
117             e.printStackTrace();
118         }
119         return result;
120     }
121 
122     /**
123      * 把一维数组转换成以split为分隔的字符串
124      * 
125      * @param arrays
126      * @param split
127      * @return String
128      */
129     public static String arrayToString(String[] arrays, String split) {
130         StringBuffer sb = new StringBuffer();
131         if (null != arrays && arrays.length > 0) {
132             for (int i = 0; i < arrays.length; i++) {
133                 sb.append((i == 0 ? "" : split) + arrays[i]);
134             }
135         }
136         return sb.toString();
137     }
138 
139     /**
140      * 把以split为分隔的字符串转换成一维数组
141      * 
142      * @param arrays
143      * @param split
144      * @return String
145      */
146     public static String arrayToString(String[][] arrays, String split) {
147         String result = "";
148         if (null != arrays && arrays.length > 0) {
149             for (int i = 1; i < arrays.length; i++) {
150                 for(int m=0;m<arrays[i].length;m++){
151                     result += (StrUtil.isNull(result) ? "" : split) + arrays[i][m];
152                 }
153             }
154         }
155         return result;
156     }
157 
158     /**
159      * 如果文本中有xml的实体字符,则要采用CDATA的方式输出
160      * 
161      * @param in
162      *            传入的文本
163      * @return 输出的处理结果文本
164      */
165     public static String formatXMLValue(String in) {
166         if (null == in || in.equals("")) {
167             return in;
168         }
169         if (in.indexOf(‘>‘) >= 0 || in.indexOf(‘<‘) >= 0 || in.indexOf(‘&‘) >= 0) {
170             char[] chars1 = new char[1];
171             chars1[0] = 91;
172             char[] chars2 = new char[1];
173             chars2[0] = 93;
174             return "<!" + new String(chars1) + "CDATA" + new String(chars1)
175                     + " " + in + " " + new String(chars2) + new String(chars2)
176                     + ">";
177         } else{
178             return in;
179         }
180     }
181 
182     /**
183      * 把字符串里出现的", <,>,&等特殊字符转换成标准可识别的字符 如字符串中包括 <,会转换成 &lt;
184      */
185     public static String formatXMLAttribute(String str) {
186         if (null == str || str.equals("")) {
187             return str;
188         }
189         String[] src = http://www.mamicode.com/{"<", ">", "\"", "‘", "&" };
190         String[] des = { "&lt;", "&gt;", "&quot", "&apos", "&amp;" };
191         String result = str;
192         for (int i = 0; i < src.length; i++) {
193             result = result.replaceAll(src[i], des[i]);
194         }
195         return result;
196     }
197 
198     /**
199      * 将分隔符的字符串转化为List对象
200      * 
201      * @param str
202      *            String-传入的分隔符字符串
203      * @param split
204      *            String-分隔符
205      * @return List对象
206      */
207     public static List stringToList(String str, String split) {
208         List list = null;
209         if (!StrUtil.isNull(str)) {
210             String args[] = str.split(split);
211             list = Arrays.asList(args);
212         }
213         return list;
214     }
215 
216     /**
217      * 将分隔符的字符串转化为String一维数组对象
218      * 
219      * @param str
220      *            String-传入的分隔符字符串
221      * @param split
222      *            String-分隔符
223      * @return String一维数组对象
224      */
225     public static String[] stringToArray(String str, String split) {
226         String array[] = new String[0];
227         if (!StrUtil.isNull(str)) {
228             array = str.split(split);
229         }
230         return array;
231     }
232 
233     /**
234      * 将列表转换成以指定分隔符的字符串
235      * 
236      * @param list :
237      *            List<String> - 含有字符串元素的列表
238      * @param split :
239      *            String - 分隔符
240      * @return String - 以指定分隔符的字符串
241      */
242     public static String listToString(final List list, final String split) {
243         String str = "";
244         if (list != null && !list.isEmpty()) {
245             for (int i = 0; i < list.size(); i++) {
246                 str += (0 == i ? "" : split) + list.get(i).toString();
247             }
248         }
249         return str;
250     }
251 
252     /**
253      * 判断一个字符串是否是正整数
254      * 
255      * @return true or false
256      */
257     public static boolean isPositiveInteger(String num) {
258         Pattern pattern = Pattern.compile("^[0-9]*[1-9][0-9]*$");
259         Matcher isNum = pattern.matcher(num);
260         return isNum.matches();
261     }
262 
263     /**
264      * 判断一个字符串是否是负整数
265      * 
266      * @return true or false
267      */
268     public static boolean isNegativeInteger(String num) {
269         Pattern pattern = Pattern.compile("^-[0-9]*[1-9][0-9]*$");
270         Matcher isNum = pattern.matcher(num);
271         return isNum.matches();
272     }
273 
274     /**
275      * 判断一个字符串是不是由整数组成的
276      * 
277      * @return true or false
278      */
279     public static boolean isNumber(String num) {
280         Pattern pattern = Pattern.compile("^[0-9]*$");
281         Matcher isNum = pattern.matcher(num);
282         return isNum.matches();
283     }
284 
285     /**
286      * 将字符串中的中文数字转换成阿拉伯数字
287      * 
288      * @param s      
289      * @return String
290      */
291     public static String chineseToNumber(String s) {
292         char[] chars = s.toCharArray();
293         char[] chineseNum = new char[] { ‘零‘, ‘一‘, ‘二‘, ‘三‘, ‘四‘, ‘五‘, ‘六‘, ‘七‘, ‘八‘, ‘九‘ };
294         for (int i = 0; i < chars.length; i++) {
295             for (int j = 0; j < chineseNum.length; j++) {
296                 if (chars[i] == chineseNum[j]) {
297                     chars[i] = String.valueOf(j).charAt(0);
298                 }
299             }
300         }
301         return new String(chars);
302     }
303 
304     /**
305      * 将字符串中的阿拉伯数字转换成中文数字
306      * 
307      * @param s
308      * @return String
309      */
310     public static String numberToChinese(String s) {
311         char[] chars = s.toCharArray();
312         char[] chineseNum = new char[] { ‘零‘, ‘一‘, ‘二‘, ‘三‘, ‘四‘, ‘五‘, ‘六‘, ‘七‘, ‘八‘, ‘九‘ };
313         for (int i = 0; i < chars.length; i++) {
314             for (int j = 0; j < chineseNum.length; j++) {
315                 if (chars[i] == j) {
316                     chars[i] = chineseNum[j];
317                 }
318             }
319         }
320         return new String(chars);
321     }
322 
323     /**
324      * 将字符串中的汉字转换成拼音
325      * 
326      * @param cnStr
327      *            汉字字符串
328      * @param type
329      *            类型:1.全拼 2.拼音首字母
330      * @return String
331      */
332     public static String chineseToPinYin(String cnStr, int type) {
333         if (null == cnStr || "".equals(cnStr.trim())) {
334             return cnStr;
335         }
336         HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
337         outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
338         outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
339         cnStr = StringUtils.deleteWhitespace(cnStr);
340         char[] chars = cnStr.toCharArray();
341         StringBuffer pinyinStr = new StringBuffer();
342         try {
343             String[] pinyinArray = null;
344             char[] firstChars = null;
345             for (int i = 0; i < chars.length; i++) {
346                 pinyinArray = PinyinHelper.toHanyuPinyinStringArray(chars[i], outputFormat);
347                 if (pinyinArray != null) {
348                     if (type == 1) {
349                         pinyinStr.append(StringUtils.join(pinyinArray, ""));
350                     } else {
351                         firstChars = pinyinArray[0].toCharArray();
352                         pinyinStr.append(ArrayUtils.toString(firstChars[0]));
353                     }
354                 }
355             }
356         } catch (BadHanyuPinyinOutputFormatCombination e) {
357             e.printStackTrace();
358         }
359         return pinyinStr.toString();
360     }
361 
362 
363     /**
364      * 编码
365      * 
366      * @param bstr
367      * @return String
368      */
369     public static String encode(byte[] bstr) {
370         return new sun.misc.BASE64Encoder().encode(bstr);
371     }
372 
373     /**
374      * 解码
375      * 
376      * @param str
377      * @return string
378      */
379     public static byte[] decode(String str) {
380         byte[] bt = null;
381         try {
382             sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
383             bt = decoder.decodeBuffer(str);
384         } catch (IOException e) {
385             e.printStackTrace();
386         }
387         return bt;
388     }
389     /**
390      * 
391      * 功能说明:将1,2,3字符串转换成‘1‘,‘2‘,‘3‘
392      * @param id  -源字符串
393      * @param split-字符串分割符
394      * @return
395      * String
396      * @author chh
397      * @Jun 28, 2012
398      */
399     public static String toSqlIds(String id,String split){
400         if(StrUtil.isNull(id)) return "‘‘";
401         String[] ids =id.split(split);
402         StringBuffer sb =new StringBuffer();
403         for(int i=0;i<ids.length;i++){
404             sb.append((i == 0 ? "" : ",") + ("‘" + ids[i] + "‘"));
405         }
406         return sb.toString();
407     }
408     
409     /**
410      * 将一维数组转化成字符
411      * @param ret -String []
412      * @return
413      */
414     public static String  toString(String [] ret){
415         StringBuffer sb =new StringBuffer();
416         for(int i=0;i<ret.length;i++){
417             if(i==ret.length-1){
418                 sb.append(ret[i]);
419             }else{
420                 sb.append(ret[i]+",");
421             }
422         }
423         return sb.toString();
424     }
425     /**
426      * 
427      * 功能说明:将Object对象转化成String对象
428      * @param value
429      * @return String
430      * @author chh
431      * @Sep 27, 2012
432      */
433     public static String objectToString(Object value){
434         String strValue;
435         if (value =http://www.mamicode.com/= null) {
436             strValue = http://www.mamicode.com/null;
437         } else if (value instanceof String) {
438             strValue =http://www.mamicode.com/ (String) value;
439         } else if (value instanceof Integer) {
440             strValue =http://www.mamicode.com/ ((Integer) value).toString();
441         } else if (value instanceof Long) {
442             strValue =http://www.mamicode.com/ ((Long) value).toString();
443         } else if (value instanceof Float) {
444             strValue =http://www.mamicode.com/ ((Float) value).toString();
445         } else if (value instanceof Double) {
446             strValue =http://www.mamicode.com/ ((Double) value).toString();
447         } else if (value instanceof Boolean) {
448             strValue =http://www.mamicode.com/ ((Boolean) value).toString();
449         } else if (value instanceof Date) {
450             DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 时间格式
451             format.setTimeZone(TimeZone.getTimeZone("GMT+8"));// 时区格式
452             strValue =http://www.mamicode.com/ format.format((Date) value);
453         } else if (value instanceof Clob) {
454             strValue =http://www.mamicode.com/ ClobUtil.clobToStr((Clob) value);
455         } else if (value instanceof Blob) {
456             strValue =http://www.mamicode.com/ BlobUtil.blobToString((Blob) value);
457         } else {
458             strValue =http://www.mamicode.com/ value.toString();
459         }
460         return strValue;
461     }
462     
463     /**
464      * 判断数组中是否包含指定字符串
465      * 
466      * @param array    字符串数据
467      * @param value 指定的字符串
468      * @return 包含则返回true,不包含返回false
469      */
470     public static boolean isArrayHasValue(String [] array,String value){
471         for(int i=0;i<array.length;i++){
472             if(array[i].equals(value))return true;
473         }
474         return false;
475     }
476     
477     /**
478      * 判断字符串是否为数字
479      * @author zhongmin
480      * @param str
481      * @return
482      */
483     public static boolean isNumeric(String str){ 
484         Pattern pattern = Pattern.compile("-?[0-9]*"); 
485         return pattern.matcher(str).matches();    
486      }
487 }

 

操作字符串的工具类