您的位置:首页 > 移动开发 > Android开发

Android常用工具类之String的工具类

2017-07-18 10:35 204 查看
对字符串处理的工具类

package com.ankoninc.utils;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* 对字符串处理的工具类
*
* Created by zengna on 2015/9/16.
*/
public class StringUtil {

public static final String ENCODING_UTF_8 = "UTF-8";

/**
* 将列表用分隔符拼接起来
* @param list
* @param separator
* @return
*/
public static String join(List<String> list, String separator) {

if (list == null) {
return "";
}

StringBuilder builder = new StringBuilder();
int len = list.size();
for (int i=0; i<len; i++) {
builder.append(list.get(i));
if (i < len - 1) {
builder.append(separator);
}
}

return builder.toString();
}

/**
* Get UTF-8 bytes of a string.
* @param s the string.
* @return the UTF-8 bytes of the string.
*/
public static byte[] getUtf8Bytes(String s) {
try {
return s.getBytes(ENCODING_UTF_8);
} catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is not supported.");
}
}

/**
* Creates an string using UTF-8 encoding.
* @return a string in UTF-8 encoding.
*/
public static String newUtf8String(byte[] data, int offset, int length) {
try {
return new String(data, offset, length, ENCODING_UTF_8);
} catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is not supported.");
}
}

/**
* Creates an string using UTF-8 encoding.
* @return a string in UTF-8 encoding.
*/
public static String newUtf8String(byte[] data) {
if (null == data) {
throw new IllegalArgumentException("data may not be null.");
}
return newUtf8String(data, 0, data.length);
}

public static String toHex(String txt) {
return toHex(StringUtil.getUtf8Bytes(txt));
}

public static String toHex(byte[] buf) {
if (null == buf) {
return "";
}

StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}

private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}

public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++) {
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
}
return result;
}

/**
* 通过正则表达式,将特殊字符过滤
* @param str
* @return
*/
public static String getValueFilter (String str) {

String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?\\s]";
Pattern pattern = Pattern.compile(regEx);
Matcher m = pattern.matcher(str);
return m.replaceAll("").trim();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息