//Utils 命名的类,通常称为工具类,封装了一些使用频繁的代码
//为了方便实用,方法都是用static
public class StringUtils {
/**
* Checks if a CharSequence is empty ("") or null.
*
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
*
* @param str
* @return
*/
public static boolean isEmpty(String str) {
return str == null || "".equals(str);
}
/**
* Checks if a CharSequence is empty (""), null or whitespace only.
*
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
*
* @param str
* @return
*/
public static boolean isBlank(String str) {
//消除空格后在和""进行比较
return str == null || "".equals(str.replace(" ", ""));
}
/**
* Reverses a String
*
* StringUtils.reverse("bat") = "tab"
*
* @param str
* @return
*/
public static String reverse(String str) {
//1、获取字符数组
char[] chars = str.toCharArray();
//2、遍历数组,交换位置
for (int i = 0;i < chars.length / 2;i++) {
char first = chars[i];
char last = chars[chars.length - 1 - i];
//增加中间变量,交换fist和last的位置
char temp = first;
chars[i] = last;
chars[chars.length -1 -i] = temp;
}
//3、把交换位置后的字符数组转化为字符串
return new String(chars);
}
/**
* Joins the elements of the provided array into a single String containing the provided list of elements.
*
* StringUtils.join(["1", "2", "3"], ";") = "1;2;3"
*
* @param array
* @param separator
* @return
*/
public static String join(String[] array, String separator) {
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < array.length; i++) {
stringBuffer.append(array[i]);//拼接字符
if (i != array.length - 1) {
stringBuffer.append(separator);//除了最后一次,都要拼接分隔符
}
}
return stringBuffer.toString();
}
}
Java String 小练习
最新推荐文章于 2024-03-26 21:26:44 发布