android TextUtils的使用
16lz
2021-01-23
今天,简单讲讲如何使用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("\n" + "\n" + "这是一个非常简单的HTML。\n" + "\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) 这个函数在我们判断字符串为空时经常可以用到。
这里注意一点,空格返回的也是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 TextView中多个空格只显示一个
- Android Studio如何轻松整理字符串到string.xml中
- Android实现DES对字符串加密
- Android中判断字符串中必须包含字母或者数字_Android
- android 复制、粘贴字符串 (判断API 11 )
- 设置TextView超过一定长度后显示省略号
- android中去掉空格--trim函数
- Android实现TextView字符串波浪式跳动
- Android的数据处理:使用annotation实现JSON字符串解析为java对象