今天,简单讲讲如何使用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的使用就讲完了。
就这么简单。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。