2019-11-2
对字符串的操作
String 也是一个类,类似于数组;
定义:
String str = “asdfghgfdsa”;
几种简单操作字符串的方法:
(1)字符串替换:
str = str.replace(“s”,”e”);
将str中的s换成e;
例:
public class Test{
public static void main(String[] args){
String str = "asdfghgfdsa";
str = str.replace("s","e");
System.out.println(str);
}
}
输出结果:
aedfghgfdea
(2)字符串分割
String[] s = str.split("f");
从字符为f的地方分割开。
例:
import java.util.*;
public class Test{
public static void main(String[] args){
String str = "asdfghgfdsa";
String[] s = str.split("f");
System.out.println(Arrays.toString(s));
}
}
输出结果:
[asd, ghg, dsa]
(3)字符串求长:
str.length();后面必须有括号;
例:
public class Test{
public static void main(String[] args){
String str = "asdfghgfdsa";
System.out.println(str.length());
}
}
输出结果:
11
(4)字符串定位:
1、 知道角标找内容:str.charAt();
例:
public class Test{
public static void main(String[] args){
String str = "asdfghgfdsa";
System.out.println(str.charAt(6));
}
}
输出结果:
g
2、 知道内容找角标:
从前往后找str.indexOf(“字符串”);
例:
public class Test{
public static void main(String[] args){
String str = "asdfghgfdsa";
System.out.println(str.indexOf('s'));
}
}
输出结果:
1
从后往前找str.lastIndexOf(“字符串”);
例:
public class Test{
public static void main(String[] args){
String str = "asdfghgfdsa";
System.out.println(str.lastIndexOf('s'));
}
}
输出结果:
9
从指定位置开始找 str.indexOf(“要找的字符”,从某个位置开始);
例:
public class Test{
public static void main(String[] args){
String str = "asdfghgfdsa";
System.out.println(str.indexOf('s',2));
}
}
输出结果:
9