package com.lesson10.example;
/*
* 三、检索属性
* 1、string.indexOf(str) 从字符串起始位置向后检索
* string.indexOf(String str,int start) 从指定位置向后检索
* (1)参数:String 检索的字符串
* int start 指定开始检索的位置
* (2)返回值:int 检索的字符串第一次出现的位置(第一个字符的位置)
* -1 未检索到指定字符串
* 2、string.lastIndexOf(str) 从字符串结束位置向前检索
* string.indexOf(String str,int end) 从指定位置向前检索
* (1)参数:String 检索的字符串
* int end 指定开始检索的位置
* (2)返回值:int 检索的字符串第一次出现的位置
* -1 未检索到指定字符串
* --------------------------------------------------
* 注意:indexOf(str)和lastIndexOf(str)都是先检索str的首字符,检测到首字符后再依次检索其他
* 字符是否存在,如果存在则检测成功,返回首字符的地址。(索引都从0开始)
* */
public class StringExample4 {
public static void main(String args[]){
String str = "Hello World!Hello CodeMonkey!";//字符的索引 0 4 6 12 18 28/** 检索Hello的位置* */System.out.println("用indexOf检索Hello,得到:"+str.indexOf("Hello"));//0,从前向后检索,返回值为首字母第一次出现的位置System.out.println("用lastIndexOf检索Hello,得到:"+str.lastIndexOf("Hello"));//12,从后向前检索,返回值为首字母第一次出现的位置/** 从指定位置检索Hello的位置(包括指定位置在内)* */System.out.println("从第5个字符开始,用indexOf检索Hello,得到:"+str.indexOf("Hello",4));//12,索引从0开始System.out.println("从第13个字符开始,用indexOf检索Hello,得到:"+str.indexOf("Hello",12));//12,检索时从指定位置开始(包括指定位置在内)/** 检索不存在的字符串* */System.out.println("用indexOf检索Helle,得到:"+str.indexOf("Helle"));System.out.println("用indexOf检索Helle,得到:"+str.indexOf("Helle"));//检索不到指定内容,则返回-1
}
}
package com.lesson10.example;
/*
* 四、拆分属性
* 1、string.substring(int start) 截取部分字符串
* string.substring(int start,int end) 截取指定部分的字符串
* (1)参数:int start 截取的起始位置
* int end 截取的结束位置
* (2)返回值:String 截取的字符串
* (3)注意:substring(int start,int end)截取的范围是[start,end)
* 2、string.split(sign) 对字符串按指定标记sign进行拆分
* (1)参数:String 指定标记
* (2)返回值:String[] 拆分后的字符串数组
* (3)注意:split不能拆分字符串没有的符号
* 3、string.replaceAll(String old, String new) 用new字符串替换old字符串
* (1)参数:String old
* String new
* (2)返回值:String 替换后的字符串
* 4、string.trim() 去掉字符串首尾的空格
* (1)参数:无
* (2)返回值:String 去掉空格后的字符串
* (3)注意:trim只去除字符串首尾的空格,对字符串中间的空格无影响
* */
public class StringExample5 {
public static void main(String args[]){String string = "Hello World!Hello CodeMonkey!";//字符索引 0 6 12 18 28/** substring()方法截取字符串* *///截取CodeMoneySystem.out.println("substring截取:"+string.substring(18)); //CodeMonkey!System.out.println("substring截取:"+string.substring(18,28));//CodeMonkey,截取的部分是索引18~27的字符//System.out.println("substring截取:"+string.substring(30));//截取部分不能超出长度或范围/** split()方法拆分字符串* */String[] strArray = string.split("!"); //将拆分后的多组字符串存入字符串数组中for(int i=0; i<strArray.length; i++){
System.out.println("拆分后的部分:" + strArray[i]);//拆分后的部分:Hello World//拆分后的部分:Hello CodeMonkey
}/** replaceAll()用new字符串替换old字符串* */String afterReplace = string.replaceAll("!", "~ ");System.out.println(afterReplace);//Hello World~ Hello CodeMonkey~/** string.trim() 去掉字符串首尾的空格* */String str = " A B C D E ";String afterTrim = str.trim();System.out.println(afterTrim); //输出:A B C D E}
}