`

StringUtil

XML 
阅读更多

 

public class StringUtil {

	/**
	 * 空字符串和null字符串返回true
	 * @param string
	 * @return
	 */
	public static boolean isNil(String string){
		return string == null || string.length() == 0;
	}

    public static boolean isNotNil(String string){
        return !isNil(string);
    }

	/**
	 * 空字符串集合和没有元素的字符串集合返回true
	 * @param string
	 * @return
	 */
	public static boolean isNil(Collection<String> strings) {
		return strings == null || strings.size() == 0;
	}

    public static boolean isNil(String[] strings) {
        return strings == null || strings.length == 0;
    }

    public static boolean isNotNil(String[] strings) {
        return !isNil(strings);
    }

    public static boolean isNotNil(Collection<String> strings) {
        return !isNil(strings);
    }
    
    public static List<String> createList(String... strings) {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < strings.length; i++) {
            list.add(strings[i]);
        }

        return list;
    }
    
    public static String[] createArray(List<String> strings) {
        String[] array = new String[strings.size()];
        for (int i = 0; i < strings.size(); i++) {
            array[i] = strings.get(i);
        }

        return array;
    }
    
    public static String trim(String string) {
        if (string == null) {
            return string;
        }
        
        return string.trim();
    }
    
    public static boolean isInStrings(String target,String... conditions){
    	for(String condition : conditions)
    	{
    		if(target.equals(condition)) return true;
    	}
    	return false;
    }
    
    public static boolean isNumber(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher match = pattern.matcher(str);
		if (match.matches() == false) {
			return false;
		} else {
			return true;
		}

	}
    
	/**
	 * 在字符串str中每隔lineSize个字符插入一个回车
	 * @param str
	 * @param lineSize
	 */
	public static String insertEnterToString(String str, int lineSize){
		if(str==null || "".equals(str))
			return null;
		
		if(lineSize>=str.length() || lineSize<=0)
			return str;
		
		String resultStr = "";
		while(str.length()>lineSize){			
			resultStr += str.substring(0, lineSize)+"\n\r";
			str = str.substring(lineSize);
		}
		resultStr += str;
		return resultStr;
	}
	
	/**
	 * 取字符串的 前length个字符
	 * @param str
	 * @param length
	 * @return
	 */
	public static String subString(String str, int length) {
		if (isNil(str) || length <= 0)
			return str;
		
		return str.length() < length ? str : str.substring(0, length);
	}
	
	public static String limitStringByBytes(String value, int len){
		if (isNil(value) || len <= 0)
			return value;
		if(value.getBytes().length<=len)
			return value;
		return new String(value.getBytes(),0,len);
	}
	public static boolean validStringByBytes(String value, int len){
		if (isNil(value) || len <= 0)
			return true;
		if(value.getBytes().length<=len)
			return true;
		return false;
	}
	
	/**
	 * null转换为""
	 * @param str
	 * @return
	 */
	public static String blankWhenNull(String str){
		return str==null?"":str;
	}
	
	public static String getStringAfter(String s,String after){
		int beginIndex = s.indexOf(after);
		if(s.length()==beginIndex+1 || beginIndex==-1)
			return "";
		return s.substring(beginIndex+1);
	}

	public static String right(String s, int length) {
        if (s == null) {
            return null;
        }
        
        assert length > 0 : "length must greater than zerio";

        if (s.length() <= length) {
            return s;
        }

        return s.substring(s.length() - length, s.length());
    }
	public static String listToString(List<String> productTagList,String split){
		String r = "";
		for(String item : productTagList){
			if(r.length()==0)
				r+=item;
			else
				r+=split+item;
		}
		return r;
	}
	
	public static boolean isNullOrEmpty(String str){
		if (null==str || 0==str.trim().length()) {
			return true;
		}
		return false;
	}

	public static final int PAD_STYLE_LEFT = 1;
	public static final int PAD_STYLE_RIGTH = 2;
	public static final int PAD_STYLE_BOTH = 3;
	
	public static String pad(String str, String padStr, int padTimes, int padStyle) {
		assert str != null : "填充目标为空";
		assert isNotNil(padStr) : "填充字符串为空";
		assert padTimes >= 0 : "填充次数小于0";
		
		String actualPadStr = "";
		for (int i = 0; i < padTimes; i++) {
			actualPadStr += padStr;
		}
		if (PAD_STYLE_LEFT == padStyle)
			return actualPadStr + str;
		else if (PAD_STYLE_RIGTH == padStyle)
			return str + actualPadStr;
		else if (PAD_STYLE_BOTH == padStyle)
			return actualPadStr + str + actualPadStr;
		else
			assert false : "不能识别填充模式";
		return str;
	}
	
	public static String pad(String str, int padTimes) {
		return pad(str, " ", padTimes, PAD_STYLE_BOTH);
	}
	//将String按len长度分割
	public static List<String> partition(String s,int len){
		List<String> ss = new ArrayList<String>();
		if(s.length()>len){
			do{
				ss.add(s.substring(0, len));
				s = s.substring(len);
			}while(s.length()>len);
		}
		ss.add(s);
		return ss;
	}
	public static String removeSameString(String s) {
		StringTokenizer token = new StringTokenizer(s, ",");
		String resultString = "";
		LinkedHashSet stringSet = new LinkedHashSet();
		int countTokens = token.countTokens();
		for (int i = 0; i < countTokens; i++) {
			stringSet.add(token.nextElement());
		}	
		Iterator it = stringSet.iterator();
		while (it.hasNext()) {
			resultString += (String) it.next() + ",";
		}
		if (StringUtil.isNotNil(resultString))
			resultString = resultString.substring(0, resultString.length() - 1);
		return resultString;
	}

	public static String obj2xml(Object obj){
		ByteArrayOutputStream o = new ByteArrayOutputStream();
		XMLEncoder e = new XMLEncoder(o);
		e.setPersistenceDelegate(BigDecimal.class,
				new DefaultPersistenceDelegate() {
				@Override
                protected Expression instantiate(Object oldInstance, Encoder out) {
				BigDecimal bd = (BigDecimal) oldInstance;
				return new Expression(oldInstance, oldInstance.getClass(), "new",
				new Object[]{bd.toString()}
				);
				}
				});
		
		e.writeObject(obj);
		e.flush();
		e.close();
		return o.toString();
	}
	
	public static Object xml2obj(String xml){
		ByteArrayInputStream i = new ByteArrayInputStream(xml.getBytes());
		XMLDecoder d = new XMLDecoder(i);
		Object obj = d.readObject();
		d.close();
		return obj;
	}
	
	/**
	 * 把半角,替换成,
	 * 
	 * @param str
	 * @return 替换后的String
	 */
	public static String replaceComma(String str){
		if (isNil(str)) {
			return str;
		}
		return str.replace(',', ',');
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T xml2obj(Class<T> clazz,String xml){
		return (T)xml2obj(xml);
	}
	
	/** 
	    * 将指定的字符串按给定的长度进行分割,返回分割后的字符串数组
	    * 如果最后一个字节是中文的半个字符,则该字节进入数组的下一条 
	    * @param originalString 指定的字符串,字符串的值不能为null 
	    * @param splitByteLength 给定字节的长度 
	    * @return 返回按照给定长度分割后的字符串数组 
	    */ 
	  public static String[] split(String originalString, int splitByteLength) 
	  { 
	      ArrayList<String> vector = new ArrayList<String>(); 
	      String strText = ""; 
	      byte arrByte[] = null; 
	      int intStartIndex = 0; 
	      int intEndIndex = 0; 
	      int index = 0; 
	      int fixCount = 0; 
	      String arrReturn[] = null; 
	      if(originalString == null) 
	          return new String[0]; 
	      if(originalString.equals("")) 
	          return new String[0]; 
	      if(originalString.trim().equals("")) 
	          return (new String[] { 
	                  "" 
	          }); 
	      if(splitByteLength <= 1) 
	          return (new String[] { 
	                  originalString 
	          }); 
	      arrByte = originalString.getBytes(); 
	      intEndIndex = 0; 
	      do 
	      { 
	          intStartIndex = intEndIndex; 
	          intEndIndex = intStartIndex + splitByteLength; 
	          if(intStartIndex >= arrByte.length) 
	              break; 
	          if(intEndIndex > arrByte.length) 
	          { 
	              intEndIndex = arrByte.length; 
	              strText = new String(arrByte, intStartIndex, intEndIndex - intStartIndex); 
	              vector.add(strText); 
	              break; 
	          } 
	          fixCount = 0; 
	          strText = new String(arrByte, intStartIndex, intEndIndex - intStartIndex); 
	          byte bytes[] = strText.getBytes(); 
	          for(index = intEndIndex - 1; index >= intStartIndex && arrByte[index] != bytes[index - intStartIndex]; index--) 
	              fixCount++; 
	            
	          if(fixCount > 0) 
	          { 
	              if(fixCount >= intEndIndex) 
	              { 
	                  fixCount = 0; 
	                  //System.out.println("split length " + splitByteLength + " is too small."); 
	              } 
	              intEndIndex -= fixCount; 
	              strText = new String(arrByte, intStartIndex, intEndIndex - intStartIndex); 
	          } 
	          vector.add(strText); 
	      } while(true); 
	      arrReturn = new String[vector.size()]; 
	      vector.toArray(arrReturn); 
	      return arrReturn; 
	  } 
	  
	  public static String objToStr(Object obj) {
		  return obj == null ? "" : String.valueOf(obj);
	  }
}

 

 

分享到:
评论

相关推荐

    StringUtil.java工具类

    StringUtil工具类java学习的好东西!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!...

    StringUtil.rar

    首先,`StringUtil.cpp`和`StringUtil.h`是C++中的源代码文件和头文件,它们定义了类`StringUtil`及其成员函数。在C++中,头文件通常用于声明类、函数、常量等,而源代码文件则包含了这些声明的实现细节。在这个案例...

    StringUtil(通过的字符处理工具类)

    `StringUtil`是一个常见的Java工具类,它包含了大量用于处理字符串的方法,可以极大地简化字符串操作,提高代码的可读性和效率。在Java开发中,我们经常会遇到对字符串进行各种操作的需求,如检查空值、分割、连接、...

    C语言实现String字符串及其函数stringUtil

    通过分析`stringUtil.c`源代码和`stringUtil.h`头文件,我们可以了解一些关键知识点。 1. **自定义字符串数据结构**:在C语言中,字符串通常以字符数组的形式存在。在`stringUtil.h`中,可能定义了一个名为`String`...

    StringUtil.java

    StringUtil.java 2100+行代码 内容丰富

    自己整理的StringUtil ,字符串处理工具类.txt

    自己整理的StringUtil ,字符串处理工具类,很全面的方法,对象之间的数据转换

    AS3-StringUtil

    《AS3-StringUtil:深入解析字符串处理工具类》 在ActionScript 3(AS3)中,处理字符串是一项常见的任务,而`StringUtil`类则是一个非常实用的工具,它提供了许多方便的方法来优化和简化字符串操作。这篇内容将...

    StringUtil工具类

    StringUtil工具类 是对String 对象封装操作

    ArrayUtil+DateUtil+FileUtil+ReguUtil+StringUtil

    这里提到的"ArrayUtil+DateUtil+FileUtil+ReguUtil+StringUtil"是五个这样的工具包,它们分别针对数组操作、日期处理、文件操作、正则表达式匹配和字符串操作提供了一系列便利的方法。 1. **ArrayUtil**: - **...

Global site tag (gtag.js) - Google Analytics