今天,簡單講講如何使用android自動的工具類TextUtils。
簡單列舉部分用法:
Log.d(TAG, "---------------------------------");
//字符串拼接
Log.d(TAG, TextUtils.concat("Hello", " ", "world!").toString());
//判斷是否為空字符串
Log.d(TAG, TextUtils.isEmpty("Hello") + "");
//判斷是否只有數字
Log.d(TAG, TextUtils.isDigitsOnly("Hello") + "");
//判斷字符串是否相等
Log.d(TAG, TextUtils.equals("Hello", "Hello") + "");
//獲取字符串的倒序
Log.d(TAG, TextUtils.getReverse("Hello", 0, "Hello".length()).toString());
//獲取字符串的長度
Log.d(TAG, TextUtils.getTrimmedLength("Hello world!") + "");
Log.d(TAG, TextUtils.getTrimmedLength(" Hello world! ") + "");
//獲取html格式的字符串
Log.d(TAG, TextUtils.htmlEncode("<html>\n" +
"<body>\n" +
"這是一個非常簡單的HTML。\n" +
"</body>\n" +
"</html>"));
//獲取字符串中第一次出現子字符串的字符位置
Log.d(TAG, TextUtils.indexOf("Hello world!", "Hello") + "");
//截取字符串
Log.d(TAG, TextUtils.substring("Hello world!", 0, 5));
//通過表達式截取字符串
Log.d(TAG, TextUtils.split(" Hello world! ", " ")[0]);
結果如下:

這其中重點講講如何使用TextUtils.isEmpty()。
是否為空字符 static boolean isEmpty(CharSequence str) 這個函數在我們判斷字符串為空時經??梢杂玫?。
這里注意一點,空格返回的也是false。其實看看源碼就知道
/**
* Returns true if the string is null or 0-length.
* @param str the string to be examined
* @return true if str is null or zero length
*/
public static boolean isEmpty(CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}
如果傳入是空格,字符串的長度不會為0,因此返回時false。為了判斷EditText輸入的是否為空字符串,可以將字符串先trim(),再傳入isEmpty,就能成功判斷了。
android TextUtils的使用就講完了。
就這么簡單。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。