import java.util.Scanner;
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("请输入字符串");
String strIn= s.nextLine();
System.out.println("请输入子串");
String strCh = s.nextLine();
boolean isCon=true; //判断是否存在字串
if(!strIn.contains(strCh)){
isCon=false;
}
if(isCon){//如果存在
System.out.print("包含该字串,");
int preStrLength = 0;
System.out.print("且查找到该子串的位置为:");
while(true){
int pos = strIn.indexOf(strCh);
if(pos==-1)break;
System.out.print((pos + preStrLength));//字串位置
System.out.print(' ');
strIn= strIn.substring(pos +strCh.length() );//截取
preStrLength +=(pos +strCh.length());
}
}else{
System.out.println("不包含该字串");
}
}
Java——给定一个字符串,判断该字符串中是否包含某个子串.如果包含,求出子串的所有出现位置.
于 2018-07-16 10:46:14 首次发布