学习小结
- 字符串截取
序号 | 方法名称 | 类型 | 描述 |
---|---|---|---|
1 | public String substring(int beginIndex) | 普通 | 由指定位置截取到结尾 |
2 | public String substring(int beginIndex, int endIndex) | 普通 | 截取指定范围的字符串 |
范例 16-12 分析字符串中取子串的方法
package com.Javastudy2;
/**
* @author Y.W.
* @date 2018年5月29日 下午11:01:57
* @Description TODO 分析字符串中取子串的方法
*/
public class P438_16_12 {
public static void main(String[] args) {
String str = "HelloJava!!!"; // 字符串
System.out.println(str.substring(5)); // 截取从指定位置到末尾的子串
System.out.println(str.substring(0, 5)); // 截取从指定位置到结束位置的子串
}
}
运行结果:
运行结果
- 字符串拆分
序号 | 方法名称 | 类型 | 描述 |
---|---|---|---|
1 | public String[] split(String regex) | 普通 | 按照指定字符串拆分 |
2 | public String[] split(String regex, int limit) | 普通 | 将字符串拆分为指定元素个数的字符串数组 |
范例 16-13 分析字符串拆分方法
package com.Javastudy2;
/**
* @author Y.W.
* @date 2018年5月29日 下午11:12:27
* @Description TODO 分析字符串拆分方法
*/
public class P429_16_13 {
public static void main(String[] args) {
String str = "hello world hello java"; // 字符串
String[] data = str.split(" "); // 按照空格拆分
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
System.out.println("----------");
String[] data1 = str.split(" ", 3); // 按照空格拆分
for (int i = 0; i < data1.length; i++) {
System.out.println(data1[i]);
}
}
}
运行结果:
运行结果
注意:
转义字符 . | \
“.”分隔,必须写成String.split("\.");
“|”分隔,必须写成String.split("\|");
“\”分隔,必须写成String.split("\\");
“|”或者,String.split("and|or")用“and”或者“or”分隔;
思考
字符串拆分需注意转义字符。
记于2018-5-29 23:38:15
By Yvan