一个实用的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;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值