(1)charAt(int index)获取指定位置的字符
public class TestString {
public static void main(String[] args) {
String sentence = "盖伦,在进行了连续8次击杀后,获得了 超神 的称号";
char c = sentence.charAt(0); //将第一字符取出来
System.out.println(c);
}
}
(2)toCharArray() 获取对应的字符串数组 Converts this string to a new character array.
public class TestString {
public static void main(String[] args) {
String sentence = "盖伦,在进行了连续8次击杀后,获得了超神 的称号";
char[] cs = sentence.toCharArray(); //获取对应的字符数组
System.out.println(sentence.length() == cs.length);
}
}
(3)截取子字符串 substring(int beginIndex, int endIndex) substring(int beginIndex)
public class TestString {
public static void main(String[] args) {
String sentence = "盖伦,在进行了连续8次击杀后,获得了 超神 的称号";
//截取从第3个开始的字符串
String subString1 = sentence.substring(3);
System.out.println(subString1);
//截取从第3个开始的字符串到(5-1)的位置的字符串 左闭右开
String subString2 = sentence.substring(3,5);
System.out.println(subString2);
}
}
(4)分隔 split(String regex) Splits this string around matches of the given regular expression.
split(String regex, int limit)
public class TestString {
public static void main(String[] args) {
String sentence = "盖伦,在进行了连续8次击杀后,获得了 超神 的称号";
//根据,进行分割,得到3个子字符串
String subSentences[] = sentence.split(",");
for (String sub : subSentences) {
System.out.println(sub);
}
}
}
(5) toLowerCase 全部变成小写
toUpperCase 全部变成大写
public class TestString {
public static void main(String[] args) {
String sentence = "Garen";
//全部变成小写
System.out.println(sentence.toLowerCase());
//全部变成大写
System.out.println(sentence.toUpperCase());
}
}
(6)indexOf 判断字符或者子字符串出现的位置,contains 是否包含子字符串
public class TestString {
public static void main(String[] args) {
String sentence = “盖伦,在进行了连续8次击杀后,获得了超神 的称号”;
System.out.println(sentence.indexOf(‘8’)); //字符第一次出现的位置
System.out.println(sentence.indexOf(“超神”)); //字符串第一次出现的位置
System.out.println(sentence.lastIndexOf(“了”)); //字符串最后出现的位置
System.out.println(sentence.indexOf(‘,’,5)); //从位置5开始,出现的第一次,的位置
System.out.println(sentence.contains(“击杀”)); //是否包含字符串”击杀
}
}
(7)replaceAll 替换所有的 replaceFirst 只替换第一个
public class TestString {
public static void main(String[] args) {
String sentence = "盖伦,在进行了连续8次击杀后,获得了超神 的称号";
String temp = sentence.replaceAll("击杀", "被击杀"); //替换所有的
temp = temp.replaceAll("超神", "超鬼");
System.out.println(temp);
temp = sentence.replaceFirst(",","");//只替换第一个
System.out.println(temp);
}
}
StringBuffer是可变长的字符串
append追加 delete 删除 insert 插入 reverse 反转
public class TestString {
public static void main(String[] args) {
String str1 = "let there ";
StringBuffer sb = new StringBuffer(str1); //根据str1创建一个StringBuffer对象
sb.append("be light"); //在最后追加
System.out.println(sb);
sb.delete(4, 10);//删除4-10之间的字符
System.out.println(sb);
sb.insert(4, "there ");//在4这个位置插入 there
System.out.println(sb);
sb.reverse(); //反转
System.out.println(sb);
}
}