android自动工具类TextUtils使用详解
2020年02月18日
作者:佚名
今天,简单讲讲如何使用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","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!",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的使用就讲完了。
就这么简单。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
以上是来客网为你收集整理的android自动工具类TextUtils使用详解全部内容,希望文章能够帮你解决android自动工具类TextUtils使用详解所遇到的程序开发问题。
如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。