Java操作字符串的工具类

操作字符串的工具类

  1 import java.io.ByteArrayOutputStream;
  2 import java.io.IOException;
  3 import java.io.PrintStream;
  4 import java.math.BigDecimal;
  5 import java.util.regex.Matcher;
  6 import java.util.regex.Pattern;
  7 
  8 public class StringUtil {
  9 
 10     /**
 11      * 过滤空NULL
 12      * @param o
 13      * @return 
 14      */
 15     public static String FilterNull(Object o) {
 16         return o != null && !"null".equals(o.toString()) ? o.toString().trim() : "" ;
 17     }
 18     
 19     /**
 20      * 是否为空
 21      * @param o
 22      * @return
 23      */
 24     public static boolean isEmpty(Object o) {
 25         if (o == null) {
 26             return true;
 27         }
 28         if ("".equals(FilterNull(o.toString()))) {
 29             return true;
 30         } else {
 31             return false;
 32         }
 33     }
 34     
 35     /**
 36      * 是否不为空
 37      * @param o
 38      * @return
 39      */
 40     public static boolean isNotEmpty(Object o) {
 41         if (o == null) {
 42             return false;
 43         }
 44         if ("".equals(FilterNull(o.toString()))) {
 45             return false;
 46         } else {
 47             return true;
 48         }
 49     }
 50     
 51     /**
 52      * 是否可转化为数字
 53      * @param o
 54      * @return
 55      */
 56     public static boolean isNum(Object o) {
 57         try {
 58             new BigDecimal(o.toString());
 59             return true;
 60         } catch (Exception e) {
 61         }
 62         return false;
 63     }
 64     
 65     /**
 66      * 是否可转化为Long型数字
 67      * @param o
 68      * @return
 69      */
 70     public static boolean isLong(Object o) {
 71         try {
 72             new Long(o.toString());
 73             return true;
 74         } catch (Exception e) {
 75         }
 76         return false;
 77     }
 78     
 79     /**
 80      * 转化为Long型数字, 不可转化时返回0
 81      * @param o
 82      * @return
 83      */
 84     public static Long toLong(Object o) {
 85         if (isLong(o)) {
 86             return new Long(o.toString());
 87         } else {
 88             return 0L;
 89         }
 90     }
 91     
 92     /**
 93      * 转化为int型数字, 不可转化时返回0
 94      * @param o
 95      * @return
 96      */
 97     public static int toInt(Object o) {
 98         if (isNum(o)) {
 99             return new Integer(o.toString());
100         } else {
101             return 0;
102         }
103     }
104     
105     /**
106      * 按字符从左截取固定长度字符串, 防止字符串超长, 默认截取50
107      * @param o
108      * @return
109      */
110     public static String holdmaxlength(Object o) {
111         int maxlength = 50;
112         if (o == null) {
113             return "";
114         }
115         return subStringByByte(o, maxlength);
116     }
117     
118     /**
119      * 从左截取固定长度字符串, 防止字符串超长, maxlength为0时默认50
120      * @param o
121      * @return
122      */
123     public static String holdmaxlength(Object o, int maxlength) {
124         maxlength = maxlength <= 0 ? 50 : maxlength;
125         if (o == null) {
126             return "";
127         }
128         return subStringByByte(o, maxlength);
129     }
130 
131     /**
132      * 按字节截取字符串
133      * @param str
134      * @param len
135      * @return
136      */
137     private static String subStringByByte(Object o, int len) {
138         if (o == null) {
139             return "";
140         }
141         String str = o.toString();
142         String result = null;
143         if (str != null) {
144             byte[] a = str.getBytes();
145             if (a.length <= len) {
146                 result = str;
147             } else if (len > 0) {
148                 result = new String(a, 0, len);
149                 int length = result.length();
150                 if (str.charAt(length - 1) != result.charAt(length - 1)) {
151                     if (length < 2) {
152                         result = null;
153                     } else {
154                         result = result.substring(0, length - 1);
155                     }
156                 }
157             }
158         }
159         return result;
160     }
161 
162     /**
163      * 逗号表达式_添加
164      * @param commaexpress 原逗号表达式 如 A,B
165      * @param newelement   新增元素 C
166      * @return A,B,C
167      */
168     public static String comma_add(String commaexpress, String newelement) {
169         return comma_rect(FilterNull(commaexpress) + "," + FilterNull(newelement));
170     }
171 
172     /**
173      * 逗号表达式_删除
174      * @param commaexpress  原逗号表达式 如 A,B,C
175      * @param delelement 删除元素 C,A
176      * @return B
177      */
178     public static String comma_del(String commaexpress, String delelement) {
179         if ((commaexpress == null) || (delelement == null) || (commaexpress.trim().equals(delelement.trim()))) {
180             return "";
181         }
182         String[] deletelist = delelement.split(",");
183         String result = commaexpress;
184         for (String delstr : deletelist) {
185             result = comma_delone(result, delstr);
186         }
187         return result;
188     }
189     
190     /**
191      * 逗号表达式_单一删除
192      * @param commaexpress  原逗号表达式 如 A,B,C
193      * @param delelement 删除元素 C
194      * @return A,B
195      */
196     public static String comma_delone(String commaexpress, String delelement) {
197         if ((commaexpress == null) || (delelement == null) || (commaexpress.trim().equals(delelement.trim()))) {
198           return "";
199         }
200         String[] strlist = commaexpress.split(",");
201         StringBuffer result = new StringBuffer();
202         for (String str : strlist) {
203           if ((!str.trim().equals(delelement.trim())) && (!"".equals(str.trim()))) {
204             result.append(str.trim() + ",");
205           }
206         }
207         return result.toString().substring(0, result.length() - 1 > 0 ? result.length() - 1 : 0);
208       }
209 
210     /**
211      * 逗号表达式_判断是否包含元素
212      * @param commaexpress 逗号表达式 A,B,C
213      * @param element C
214      * @return true
215      */
216     public static boolean comma_contains(String commaexpress, String element) {
217         boolean flag = false;
218         commaexpress = FilterNull(commaexpress);
219         element = FilterNull(element);
220         if (!"".equals(commaexpress) && !"".equals(element)) {
221             String[] strlist = commaexpress.split(",");
222             for (String str : strlist) {
223                 if (str.trim().equals(element.trim())) {
224                     flag = true;
225                     break;
226                 }
227             }
228         }
229         return flag;
230     }
231 
232     /**
233      * 逗号表达式_取交集
234      * @param commaexpressA 逗号表达式1  A,B,C
235      * @param commaexpressB 逗号表达式2  B,C,D
236      * @return B,C
237      */
238     public static String comma_intersect(String commaexpressA, String commaexpressB) {
239         commaexpressA = FilterNull(commaexpressA);
240         commaexpressB = FilterNull(commaexpressB);
241         StringBuffer result = new StringBuffer();
242         String[] strlistA = commaexpressA.split(",");
243         String[] strlistB = commaexpressB.split(",");
244         for (String boA : strlistA) {
245             for (String boB : strlistB) {
246                 if (boA.trim().equals(boB.trim())) {
247                     result.append(boA.trim() + ",");
248                 }
249             }
250         }
251         return comma_rect(result.toString());
252     }
253 
254     /**
255      * 逗号表达式_规范
256      * @param commaexpress  逗号表达式  ,A,B,B,,C
257      * @return A,B,C
258      */
259     public static String comma_rect(String commaexpress) {
260         commaexpress = FilterNull(commaexpress);
261         String[] strlist = commaexpress.split(",");
262         StringBuffer result = new StringBuffer();
263         for (String str : strlist) {
264             if (!("".equals(str.trim())) && !("," + result.toString() + ",").contains("," + str + ",") && !"null".equals(str)) {
265                 result.append(str.trim() + ",");
266             }
267         }
268         return result.toString().substring(0, (result.length() - 1 > 0) ? result.length() - 1 : 0);
269     }
270     
271     /**
272      * 逗号表达式_反转
273      * @param commaexpress A,B,C
274      * @return C,B,A
275      */
276     public static String comma_reverse(String commaexpress) {
277         commaexpress = FilterNull(commaexpress);
278         String[] ids = commaexpress.split(",");
279         StringBuffer str = new StringBuffer();
280         for (int i = ids.length - 1; i >= 0; i--) {
281             str.append(ids[i] + ",");
282         }
283         return comma_rect(str.toString());
284     }
285 
286     /**
287      * 逗号表达式_获取首对象
288      * @param commaexpress A,B,C
289      * @return A
290      */
291     public static String comma_first(String commaexpress) {
292         commaexpress = FilterNull(commaexpress);
293         String[] ids = commaexpress.split(",");
294         System.out.println("length:" + ids.length);
295         if ((ids != null) && (ids.length > 0)) {
296             return ids[0];
297         }
298         return null;
299     }
300 
301     /**
302      * 逗号表达式_获取尾对象
303      * @param commaexpress A,B,C
304      * @return C
305      */
306     public static String comma_last(String commaexpress) {
307         commaexpress = FilterNull(commaexpress);
308         String[] ids = commaexpress.split(",");
309         if ((ids != null) && (ids.length > 0)) {
310             return ids[(ids.length - 1)];
311         }
312         return null;
313     }
314 
315     /**
316      * 替换字符串,支持字符串为空的情形
317      * @param strData
318      * @param regex
319      * @param replacement
320      * @return
321      */
322     public static String replace(String strData, String regex, String replacement) {
323         return strData == null ? "" : strData.replaceAll(regex, replacement);
324     }
325         
326     /**
327      * 字符串转为HTML显示字符
328      * @param strData
329      * @return
330      */
331     public static String String2HTML(String strData){
332         if( strData == null || "".equals(strData) ){
333             return "" ;
334         }
335         strData = replace(strData, "&", "&amp;");
336         strData = replace(strData, "<", "&lt;"); 
337         strData = replace(strData, ">", "&gt;");
338         strData = replace(strData, "\"", "&quot;");
339         return strData;
340     }
341     
342     /**     * 把异常信息转换成字符串,以方便保存 */
343     public static String getexceptionInfo(Exception e){
344         ByteArrayOutputStream baos = new ByteArrayOutputStream();
345         try{
346             e.printStackTrace(new PrintStream(baos));
347         }finally{
348             try {
349                 baos.close();
350             } catch (IOException e1) {
351                 e1.printStackTrace();
352             }
353         }
354         return baos.toString();
355     }
356     
357     /** 过滤特殊符号 */ 
358     public static String regex(String str){
359         Pattern pattern = Pattern.compile("[0-9-:/ ]");// 中文汉字编码区间
360         Matcher matcher;
361         char[] array = str.toCharArray();
362         for (int i = 0; i < array.length; i++) {
363             matcher = pattern.matcher(String.valueOf(array[i]));
364             if (!matcher.matches()) {// 空格暂不替换
365                 str = str.replace(String.valueOf(array[i]), "");// 特殊字符用空字符串替换
366             }
367         }
368          
369         return str;    
370     }
371     
372     public static String comma_insert(String commaexpress, String newelement,int index){
373         int length = commaexpress.length();
374         if ( index > length ) {
375             index = length;
376         }else if ( index < 0){
377             index = 0;
378         }
379         String result = commaexpress.substring(0, index) + newelement + commaexpress.substring(index, commaexpress.length());
380         return result;
381     }
382     
383     /**
384      * 将"/"替换成"\"
385      * @param strDir
386      * @return
387      */
388     public static String changeDirection(String strDir) {
389         String s = "/";
390         String a = "\\";
391         if (strDir != null && !" ".equals(strDir)) {
392             if (strDir.contains(s)) {
393                 strDir = strDir.replace(s, a);
394             }
395         }
396         return strDir;
397     }
398 
399     /**
400      * 去除字符串中 头和尾的空格,中间的空格保留
401      * 
402      * @Title: trim
403      * @Description: TODO
404      * @return String
405      * @throws
406      */
407     public static String trim(String s) {
408         int i = s.length();// 字符串最后一个字符的位置
409         int j = 0;// 字符串第一个字符
410         int k = 0;// 中间变量
411         char[] arrayOfChar = s.toCharArray();// 将字符串转换成字符数组
412         while ((j < i) && (arrayOfChar[(k + j)] <= ' '))
413         ++j;// 确定字符串前面的空格数
414         while ((j < i) && (arrayOfChar[(k + i - 1)] <= ' '))
415         --i;// 确定字符串后面的空格数
416         return (((j > 0) || (i < s.length())) ? s.substring(j, i) : s);// 返回去除空格后的字符串
417     }
418     /**
419      * 得到大括号中的内容
420      * @param str
421      * @return
422      */
423     public static String getBrackets(String str) {
424         int a = str.indexOf("{");
425         int c = str.indexOf("}");
426         if (a >= 0 && c >= 0 & c > a) {
427             return (str.substring(a + 1, c));
428         } else {
429             return str;
430         }
431     }
432 
433     /**
434      * 将字符串中所有的,替换成|
435      * 
436      * @param str
437      * @return
438      */
439     public static String commaToVerti(String str) {
440         if (str != null && !"".equals(str) && str.contains(",")) {
441             return str.replaceAll(",", "|");
442         } else {
443             return str;
444         }
445     }
446 
447     /**
448      * 去掉字符串中、前、后的空格
449      * @param args
450      * @throws IOException
451      */
452     public static String extractBlank(String name) {
453         if (name != null && !"".equals(name)) {
454             return name.replaceAll(" +", "");
455         } else {
456             return name;
457         }
458     }
459 
460     /**
461      * 将null换成""
462      * @param str
463      * @return
464      */
465     public static String ConvertStr(String str) {
466         return str != null && !"null".equals(str) ? str.trim() : "";
467     }
468     
469     public static void main(String[] args){
470         System.out.println(isNum("a"));
471         System.out.println(isNum("-1"));
472         System.out.println(isNum("01"));
473         System.out.println(isNum("1E3"));
474         System.out.println(isNum("1.a"));
475         System.out.println(isLong("014650"));
476         System.out.println(Long.parseLong("014650"));
477     }
478 }

 

posted @ 2016-08-11 13:16  SummerChill  阅读(8646)  评论(0编辑  收藏  举报