1.获取指定位置的字符
package character;
public class TestString {
public static void main(String[] args) {
String sentence = "盖伦,在进行了连续8次击杀后,获得了 超神 的称号";
char c = sentence.charAt(0);
System.out.println(c);
}
}
这个地方的输出就是盖
2.获取字符串的对应数组
用toCharArray方法
package character;
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方法
、ackage character;
public class TestString {
public static void main(String[] args) {
String sentence = "盖伦,在进行了连续8次击杀后,获得了 超神 的称号";
//截取从第3个开始的字符串 (基0)
String subString1 = sentence.substring(3);
System.out.println(subString1);
//截取从第3个开始的字符串 (基0)
//到5-1的位置的字符串
//左闭右开
String subString2 = sentence.substring(3,5);
System.out.println(subString2);
}
}
4.有时候字符串里面会有分割字符,比如逗号,冒号,想要根据这些来分开字符串,我们这个时候就要用到split操作
package character;
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.有时候一些字符串包含一些首尾的空格,我们想要去掉这些空格,就要用到trim方法
package character;
public class TestString {
public static void main(String[] args) {
String sentence = " 盖伦,在进行了连续8次击杀后,获得了 超神 的称号 ";
System.out.println(sentence);
//去掉首尾空格
System.out.println(sentence.trim());
}
}
6.大小写转换
这个就是常见的大写字符和小写字符的转换方法
toLowercase和toUppercase
package character;
public class TestString {
public static void main(String[] args) {
String sentence = "Garen";
//全部变成小写
System.out.println(sentence.toLowerCase());
//全部变成大写
System.out.println(sentence.toUpperCase());
}
}
7.字符串中某个字符的定位
要用到indexOf方法,还有一个contains方法判断是否包含某个字符串
package character;
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("击杀")); //是否包含字符串"击杀"
}
}
8.替换方法
replaceAll是替换所有的符合条件的字符
replaceFirst是只替换第一个符合条件的字符
package character;
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);
}
}