一:搜索字符出现的位置
①搜索第一个出现的字符ch(或是字符串value)
用的是indexOf(int ch)或是indexOf(String value)、
找到了就会返回一个值 ,这个值是从0开始的,找不到返回-1.
String s1= "青春无悔";
int index = s1.indexOf("1");
System.out.println(index);
int i = s1.indexOf("悔");
System.out.println(i);
②是搜索最后一个出现的字符ch(或是字符串value)它的意思就是这个字符在这个字符串中出现了不止一次,而它所找到的就是最后一次出现该字符的位置返回值跟上面的一样。
用lastIndexOf(int ch)或是 lastIndexOf(String value)
String s2=" 青春 无 悔 无 悔 青 春 ";
int s3 = s2.lastIndexOf("春");
System.out.println(s3);
二: 提取字符串的某部分
①:提取从位置索引开始的字符串部分(也就是从这个位置开始(包括这个位置)以后的所有字符串)
用的是substring(int index)方法
String s2="青春 无 悔 无 悔 青 春 ";
System.out.println("+++++"+s2);
String re = s2.substring(1);
System.out.println(re);
②提取beginindex和endindex之间的字符串部分(从beginindex位置开始(包括beginindex)到endindex位置 (不包括endindex))
String s2="青春 无 悔 无 悔 青 春 ";
System.out.println("+++++"+s2);
String re = s2.substring(1,6);
System.out.println(re);
③ 返回一个前后不含空格的调用字符串的副本 也就是返回的是字符串最前面和最后面没有空格
String s2=" 青春 无 悔 无 悔 青 春 ";
String s4 = s2.trim();
System.out.println(s4);
三:字符串的拆分
用的是String类的split()方法
String words = "长亭外 古道边 芳草碧连天 晚风扶 柳笛声残 夕阳山外山";
System.out.println("****原歌词********"+words);
System.out.println("**********************");
String printword = words.split(" ");//按空格拆分
System.out.println(printword[0]);
for (int j = 0; j < printword.length; j++) {
System.out.println(printword[j]);
}
拆分有很多方式如words.split(,)按逗号拆分