不耻下问:Java语言怎么实现类似C++的strstr函数的功能,有没有对应的功能可以调用呢
import java.util.Scanner;
/**
* 实现strStr()函数,给定haystack字符串和一个needle字符串,
* 在haystack字符串中找出needle字符串出现的第一个位置(从0开始)。如果不存在,则返回-1。
*/
public class Realize_strStr {
public static void main(String[] args) {
System.out.println("请输入haystack字符串:");
String haystack = new Scanner(System.in).nextLine();
System.out.println("请输入needle字符串");
String needle = new Scanner(System.in).nextLine();
System.out.println("结果为:"+Solution(haystack,needle));
}
public static int Solution(String haystack, String neddle){
for (int i = 0; i < haystack.length()-neddle.length() + 1; i++) { //从0开始,到haystack剩余长度小于neddle为止
if (haystack.substring(i,i+neddle.length()).equals(neddle)) return i;//判断到此为止haystack内是否存在neddle
}
return -1;
}
}
String a = "aaaabbbbccc";
System.out.println(a.contains("ab"));
System.out.println(a.contains("abc"));
System.out.println(a.indexOf("ab"));
System.out.println(a.indexOf("abc"));
一种是是否包含来判断,一种是首次出现这个子字符串位置来判断,-1表示没有