1. 程式人生 > >Java常見幫助類(2)字串處理類

Java常見幫助類(2)字串處理類

閒話少說,下面幫組類主要是實現字串判空,字串相等,字串替換,字串填補等十幾個功能,具體看程式碼:

/**
 * 字串處理類
 * 
 * 
 */
public class StringUtil {


/**
* 判斷字串是否為空
* 
* @param str
* @return
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0)
return true;
for (int i = 0; i < strLen; i++)
if (!Character.isWhitespace(str.charAt(i)))
return false;


return true;
}


public static boolean isNotBlank(String str) {
return !isBlank(str);
}


public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}


public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}


/**
* 以type為分界符分離str字串,返回分離後的陣列
* 
* @param str
*            待處理字串
* @param type
*            分界符
* 
* @return array 處理後的字串陣列
*/
public static String[] split(String str, String type) {


int begin = 0;
int pos = 0;
String tempstr = "";
String[] array = null;
Vector vec = null;
int len = str.trim().length();
str = str + type;


if (len > 0) {
while (str.length() > 0) {


if (vec == null) {
vec = new Vector();
}


pos = str.indexOf(type, begin);
tempstr = str.substring(begin, pos);
str = str.substring(pos + 1, str.length());
vec.add(tempstr);
}
} else {
vec = new Vector();
vec.add("");
}
if (vec != null) {
array = new String[vec.size()];


for (int i = 0; i < vec.size(); i++) {
array[i] = (String) vec.get(i);
}
} else {
array = new String[0];
}


return array;
}


/**
* 按長度把字串前補0
* 
* @param s
*            需要補位字串物件
* @return len 該字串的長度
*/
public static String len(String s, int len) {


if (!notNull(s))
s = "";


int length = len - s.length();
for (int i = 0; i < length; i++) {
s = "0" + s;
}
return s;
}


/**
* 判斷字串是否為空
* 
* 
* @param s
*            需要判斷字串物件
* @return true 表示不為空 false 為空
* @throws java.lang.Exception
*/
public static boolean notNull(String s) {


if (s == null || s.trim().length() <= 0 || "".equals(s)
|| "null".equals(s))
return false;
else
return true;
}


/**
* 返回一個布林值,表示兩個字串是否相等
* 
* 
* @param objstr
*            字串物件
* 
* @param bjstr
*            字串物件
* 
* @return false 表示不相等 true 相等
* @throws java.lang.Exception
*/
public static boolean equals(String objstr, String bjstr) {


boolean lean = false;
lean = (objstr != null) && objstr.equals(bjstr);


return lean;
}


/**
* 替換source中的str1為str2
* 
* @param source
*            待替換的字串
* 
* @param str1
*            待替換的字元
* @param str2
*            替換的字元
* 
* @return java.lang.String 替換後的字串
*/
public static String replace(String source, char str1, String str2) {
return replace(source, String.valueOf(str1), str2);
}


/**
* 替換掉source字串中的所有需要替換的字元
* 
* @param source
* @param str1
* @param str
* @return
*/
public static String replaceSome(String source, String... str) {
String sourcestr = source;
for (String replicestr : str) {
sourcestr = replace(sourcestr, String.valueOf(replicestr), "");
}
return sourcestr;
}


/**
* 替換source中的str1為str2
* 
* @param source
*            待替換的字串
* 
* @param str1
*            待替換的字元
* @param str2
*            替換的字元
* 
* @return java.lang.String 替換後的字串
*/
public static String replace(String source, String str1, String str2) {
if (source == null)
return "";
String desc = "";
int posstart = 0;
int posend = source.indexOf(str1, 0);
int len = source.length();
while (posend >= 0 && posstart < len) {
desc += source.substring(posstart, posend) + str2;
posstart = posend + str1.length();
posend = source.indexOf(str1, posstart);
}
if (posstart < len)
desc += source.substring(posstart, len);
return desc;
}


/**
* 替換source中的"\n"為"換行符"
* 
* @param source
*            待替換的字串
* 
* @return java.lang.String 替換後的字串
*/
public static String replace(String content) {
String[] tempValue = null;
if (content != null) {
if (content.indexOf("\n") != -1) {
tempValue = StringUtil.split(content, "\n");
}
if (tempValue != null && tempValue.length > 0) {
content = "";
for (int i = 0; i < tempValue.length; i++) {
content += tempValue[i] + "<br>";
}
content = content.substring(0, content.length() - 4);
}
}
return content;
}


/**
* 將字串列表轉換成字串陣列
* 
* @param list
*            List 字串列表
* 
* @return String[]
*/
public static String[] list2Array(List list) {
String[] strs = new String[list.size()];
for (int i = 0; i < strs.length; i++) {
strs[i] = (String) list.get(i);
}
return strs;
}


/**
* 將字串陣列轉換成字串列表
* 
* @param array
*            String[] array 字串陣列
* 
* @return List 字串列表
*/
public static List array2List(String[] array) {
List list = null;
if (array != null) {
list = new ArrayList(array.length);
for (int i = 0; i < array.length; i++) {
list.add(list.get(i));
}
}
return list;
}


/**
* 過濾Html的特殊字元
*/
public static String htmlEscape(String in) {
StringBuffer out = new StringBuffer();
for (int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
switch (c) {
case '"':
out.append(""");
break;
case '&':
out.append("&");
break;
case '<':
out.append("<");
break;
case '>':
out.append(">");
break;
default:
out.append(c);
break;
}
}
return out.toString();
}


/**
* 取String最後幾位
*/
public static String getStrLast(String str, int i) {
return str.substring(str.length() - i, str.length());
}


/**
* 判斷是該字串是否是圖片或者是圖片連線 jpg,bmp,gif,jpeg
*/
public static boolean isImage(String str) {
boolean flag = false;
String type1 = StringUtil.getStrLast(str, 4);
if (type1.equals(".jpg") || type1.equals(".JPG")) {
flag = true;
}
if (type1.equals(".bmp") || type1.equals(".BMP")) {
flag = true;
}
if (type1.equals(".gif") || type1.equals(".GIF")) {
flag = true;
}


String type2 = StringUtil.getStrLast(str, 5);
if (type2.equals(".jpeg") || type2.equals(".GPEG")) {
flag = true;
}
return flag;
}


public static String urlFilter(String str) {
String temp = "http://www.";
String temp1 = "www.";
String temp2 = "http://";
if (str.indexOf(temp) > -1) {


} else {
if (str.indexOf(temp2) > -1) {


} else {
if (str.indexOf(temp1) > -1) {
str = "http://" + str;
} else {
str = temp2 + str;
}
}


}


String s = str.substring(7);
if (s.indexOf("/") > 0) {


} else {
char c = str.charAt(str.length() - 1);


if ("/".equals(String.valueOf(c))) {


} else {
str = str + "/";
}
}


return str;
}


public static String rssUrlEcode(String rss) {
if (isBlank(rss)) {
return "";
}
String re = "";
try {
re = java.net.URLEncoder.encode("\"" + rss + "\"", "utf-8");
} catch (UnsupportedEncodingException e) {
System.out.println("轉碼異常,UnsupportedEncodingException");
e.printStackTrace();
}
return re;
}


/**
* Replaces the first substring of this string that matches the given key
* with the given replacement.
* 
* @param str
*            The String to be replaced
* @param key
*            Key within the String to be searched and replaced
* @param replacement
*            The String used to replace
* @return The String with the first occurence of the key value replaced.
*/
public static String replaceFirst(String str, String key, String replacement) {
StringBuffer result = new StringBuffer(str);


int pos = str.indexOf(key);


if (pos >= 0) {
result.replace(pos, pos + key.length(), replacement);
// System.out.println( "result = " + result );
}
return result.toString();
}


public static String replaceChar(String str) {


return str.replace("\\", "/");
}


/**
* 對double資料進行取精度.
* <p>
* For example: <br>
* double value = 100.345678; <br>
* double ret = round(value,4,BigDecimal.ROUND_HALF_UP); <br>
* ret為100.3457 <br>
* 
* @param value
*            double資料.
* @param scale
*            精度位數(保留的小數位數).
* @param roundingMode
*            精度取值方式.
* @return 精度計算後的資料.
*/
public static double round(double value, int scale, int roundingMode) {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(scale, roundingMode);
double d = bd.doubleValue();
bd = null;
return d;
}


/**
* 得到檔名的字尾
* 
* @param args
*/
public static String getHouzhui(String string) {


int t = string.lastIndexOf(".");
String str = string.substring(t + 1);
return str;
}


/**
* 擷取字串作為檔案標題
*/
public static String getTitleSubString(String str) {
Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
Matcher m = p.matcher(str);
String after = m.replaceAll("");


String temp = after.replaceAll("\\p{P}", "");


return temp.substring(0, 10).trim();
}


// 得到字串裡的大寫個數
public static int getUpperCaseNum(String str) {
int count = 0;
Pattern p = Pattern.compile("[A-Z]");
Matcher m = p.matcher(str);
while (m.find()) {
count++;
}
return count;
}


// 得到字串裡的小寫個數
public static int getLowerCaseNum(String str) {
int count = 0;
Pattern p = Pattern.compile("[a-z]");
Matcher m = p.matcher(str);
while (m.find()) {
count++;
}
return count;
}


// 得到字串裡的數字個數
public static int getFigureNum(String str) {
int count = 0;
Pattern p = Pattern.compile("\\d");
Matcher m = p.matcher(str);
while (m.find()) {
count++;
}
return count;
}


// 得到字串裡特殊字元個數
public static int getSpecialCharNum(String str) {
int count = 0;
Pattern p = Pattern.compile("[\\W_]");
Matcher m = p.matcher(str);
while (m.find()) {
count++;
}
return count;
}


// 去掉最後一個字元
public static String removeLastChar(String str) {
if (str != "") {
str = str.substring(0, str.length() - 1);
}
return str;
}


/**
* 去除重複項
* 
* @param list
* @return list
*/
public static List removeDuplicateWithOrder(List list) {
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext();) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
return newList;
}


/**
* 位元組轉換成字串以兆的形式顯示
* 
* @param size
* @return
*/
public static String formate(int size) {
StringBuffer sb = new StringBuffer();
sb.append(String.valueOf((int) (size / 1024)));
sb.append("M");
return sb.toString();
}


/**
* 根據stringSource包含的字元與number生成固定長度的隨機字串
* 
* @param number
* @param stringSource
* @return
*/
public static String getFixedSizeRandomStr(int length, String stringSource) {
Random random = new Random();
StringBuffer sBuffer = new StringBuffer();
if (length > 0) {
for (int i = 0; i < length; i++) {
int number = random.nextInt(stringSource.length());
sBuffer.append(stringSource.charAt(number));
}
}
return sBuffer.toString();
}


/*
* 
* 格式化數字
*/
public static String formatNumber(Object number, String pattern) {
String numberFormated = "";
if (number != null) {
try {
numberFormated = new DecimalFormat(pattern).format(number);
} catch (Exception e) {
e.printStackTrace();
}
}


return numberFormated;
}


/**
* 得到某個字串標記的前面字串
*/


public static String getHeadWord(String str, String mark) {
int markNum = str.indexOf(mark);
String newWord = str.substring(0, markNum);
return newWord;
}


public static void main(String[] args) {
/*
* String temp = "www.replays.net"; String temp1 = "replays.net";
* 
* String str = StringUtil.urlFilter(temp); System.out.println(str);
* String st1r = StringUtil.urlFilter(temp1); System.out.println(st1r);
* 
* // System.out.println(temp.indexOf("http://d"));
* System.out.println(rssUrlEcode("行動通訊"));
* System.out.println(rssUrlEcode("移動"));
* System.out.println(rssUrlEcode("www"));
* System.out.println(rssUrlEcode("aaaaaaaaa"));
*/


System.out.println(replaceSome("abcdefgh", "a", "b", "c"));
}


/**
* 
* @描述: 轉換url 去掉 http:// 和 https://
* 
*/
public static String formatUrl(String url) {
if (StringUtils.isBlank(url)) {
return "";
}
if (url.startsWith("https://")) {
url = url.substring(8);
} else if (url.startsWith("http://")) {
url = url.substring(7);
}
return url;
}
}