今天,簡單講講如何使用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)); //通過表達式截取字符串 Log.d(TAG, TextUtils.split(" Hello world! ", " ")[0]); 結果如下:

這其中重點講講如何使用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的使用就講完了。
就這么簡單。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點
疑難解答
圖片精選