1. 程式人生 > >一個實用的java字串工具類(擷取,去尾,轉碼)

一個實用的java字串工具類(擷取,去尾,轉碼)

package com.xx.sisp.iface.common.util;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;

/**
* Created by zetting on 2016/8/16.
* Description:字串操作工具
*/
public class StringUtil {

/**
 * 擷取字串
 * @param str 待擷取的字串
 * @param start 擷取起始位置 ( 1 表示第一位 -1表示倒數第1位)
 * @param end 擷取結束位置 (如上index)
 * @return
 */
public static String sub(String str,int start,int end){
    String result = null;

    if(str == null || str.equals(""))
        return "";

    int len=str.length();
    start = start < 0 ? len+start : start-1;
    end= end < 0 ? len+end+1 :end;

    return str.substring(start, end);
}

/**
 * 將字串str的格式轉為utf-8
 * @param str
 * @return
 */
public static String toUTF_8(String str){
    String result=null;
    try {
        if(StringUtils.isEmpty(str)){
            return str;
        }
        result = new String(str.getBytes("iso-8859-1"),"utf-8");
        return result;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return result;
}

/**
* 若str字串已tag結束則剔除tag
* @param str 待剔除的字串
* @param tag 要剔除的標籤
* @return 剔除後的字串
* @throws Exception
*/
public static String trimEnd(String str,String tag) throws Exception{
String result = str;
if(str == null || str.equals(“”)){
return str;
}
if(tag == null || tag.equals(“”)){
throw new Exception(“引數tag 不能為null或‘’ “);
}

int tagPosition = str.lastIndexOf(tag);
if(tagPosition+tag.length() == str.length()){
    result = str.trim().substring(0,tagPosition);
}
return result;

}
}