溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

android自動工具類TextUtils使用詳解

發(fā)布時間:2020-09-05 20:54:03 來源:腳本之家 閱讀:136 作者:bzlj2912009596 欄目:移動開發(fā)

今天,簡單講講如何使用android自動的工具類TextUtils。

簡單列舉部分用法:

Log.d(TAG, "---------------------------------"); 
  //字符串拼接 
  Log.d(TAG, TextUtils.concat("Hello", " ", "world!").toString()); 
  //判斷是否為空字符串 
  Log.d(TAG, TextUtils.isEmpty("Hello") + ""); 
  //判斷是否只有數(shù)字 
  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>")); 
  //獲取字符串中第一次出現(xiàn)子字符串的字符位置 
  Log.d(TAG, TextUtils.indexOf("Hello world!", "Hello") + ""); 
  //截取字符串 
  Log.d(TAG, TextUtils.substring("Hello world!", 0, 5)); 
  //通過表達(dá)式截取字符串 
  Log.d(TAG, TextUtils.split(" Hello world! ", " ")[0]); 

結(jié)果如下:

android自動工具類TextUtils使用詳解

這其中重點講講如何使用TextUtils.isEmpty()。

是否為空字符 static boolean  isEmpty(CharSequence str) 這個函數(shù)在我們判斷字符串為空時經(jīng)??梢杂玫?。

這里注意一點,空格返回的也是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的使用就講完了。

就這么簡單。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI