gitee Kotlin学习日志(二)数据类型 - android:layout_height=“wrap_content”
==================================================================
3.1字符串与基本类型的转换
这里我们对比一下Java的转换方式,如下表:
| 字符串转换目标 | Kotlin的转换方式 | Java的转换方式 |
| — | — | — |
| 字符串转整型 | 字符串变量的toInt方法 | Integer.parseInt(字符串变量) |
| 字符串转长整型 | 字符串变量的toLong方法 | Long.parseInt(字符串变量) |
| 字符串转浮点数 | 字符串变量的toFloat方法 | Float.parseInt(字符串变量) |
| 字符串转双精度数 | 字符串变量的toDouble方法 | Double.parseInt(字符串变量) |
| 字符串转布尔类型 | 字符串变量的toBoolean方法 | Boolean.parseInt(字符串变量) |
| 字符串转字符数组 | 字符串变量的toCharArray方法 | 字符串变量的toCharArray方法 |
可以看到Kotlin相对于Java的转换要简单一些,通过方法即可实现。
3.2字符串的常用方法
常用方法:查找子串、替换子串、截取指定位置的子串、按特定字符分隔子串等,在这方面Kotlin基本兼容Java的相关方法,
1.查找子串,都调用indexOf方法。
2.截取指定位置子串,都调用substring方法。
3.替换子串,都调用replace方法。
4.按特定字符分隔子串,都调用split方法
下面是查找和截取的使用示例:
布局文件代码
activity_main.xml
xmlns:app=“http://schemas.android.com/apk/res-auto”
xmlns:tools=“http://schemas.android.com/tools”
android:orientation=“vertical”
android:gravity=“center_horizontal”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=“.MainActivity”>
android:layout_marginTop=“20dp”
android:gravity=“center”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”>
android:textColor=“#000”
android:text=“初始值:”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content” />
android:textColor=“#000”
android:text=“200.56”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:id=“@+id/tv_data”/>
android:visibility=“gone”
android:id=“@+id/result_lay”
android:layout_marginTop=“20dp”
android:gravity=“center” 拼多多帮助力入口
android:layout_width=“match_parent”
android:layout_height=“wrap_content”>
android:textColor=“#000”
android:text=“结果值:”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content” />
android:textColor=“#000”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:id=“@+id/tv_result”/>