高分悬赏:Java语言怎么实现字符串中查找是否包含另一个字符串呢
高分悬赏:Java语言怎么实现字符串中查找是否包含另一个字符串呢
高分悬赏:Java语言怎么实现字符串中查找是否包含另一个字符串呢
如果要重复造轮子,自己实现,可以看看 String 的 contains 方法:
public boolean contains(CharSequence s) {
return indexOf(s.toString()) > -1;
}
如果要用来判断是否包含的话,直接调用库函数就可以了。
contains() 方法
public class SearchStringEmp {
public static void main(String[] args) {
String strOrig = "Google Runoob Taobao";
int intIndex = strOrig.indexOf("Runoob");
if(intIndex == - 1){
System.out.println("没有找到字符串 Runoob");
}else{
System.out.println("Runoob 字符串位置 " + intIndex);
}
}
}
#参以上考实例
String.indexOf() 这个方法返回 该方法传入一个参数,并且返回被查找字符串的第一次出现的位置(第一个位置返回0,以此类推),失败返回-1.
测试代码仅供参考
public class StringMatch {
/**
* kmp算法比较
* @param str 目标串
* @param dest 模式串
* @param next next值数组
* @return 第一个匹配的目标串的首位置索引
*/
public static int stringMatchByKmp(String str, String dest,int[] next){
for(int i = 0, j = 0; i < str.length(); i++){
while(j > 0 && str.charAt(i) != dest.charAt(j)){
j = next[j - 1];
}
if(str.charAt(i) == dest.charAt(j)){
j++;
}
if(j == dest.length()){
return i-j+1;
}
}
return 0;
}
/**
* 模式串中字符的next值
* @param dest 模式串
* @return 模式串中字符的next值
*/
public static int[] next(String dest){
int[] next = new int[dest.length()];
next[0] = 0;
for(int i = 1,j = 0; i < dest.length(); i++){
while(j > 0 && dest.charAt(j) != dest.charAt(i)){
j = next[j - 1];
}
if(dest.charAt(i) == dest.charAt(j)){
j++;
}
next[i] = j;
}
return next;
}
public static void main(String[] args) {
System.out.println(stringMatchByKmp("aabcabc","abc",next("abc")));
}
大佬,请采纳
public static void main(String[] args) {
System.out.print("请输入第一个字符串:");
Scanner sc = new Scanner(System.in);
String str1 = sc.next();
System.out.print("请输入第二个字符串:");
String str2 = sc.next();
String max = null;
String min = null;
int m = str1.length();
int n = str2.length();
min = m <= n ? str1 : str2;
max = m > n ? str1 : str2;
String tmp = null; //临时子串
int index = 0; //存放最长子串在最长字符串中的起始索引
int len = 0; //存放最长子串的长度
int[] arr1 = new int[min.length()];
int flag = 0;
// 遍历长度为i的min子串,从0开始
for (int i = min.length(); i >= 1; i--) {
// 遍历取出最短字符串中所有可能出现的子串
for (int j = 0; j <= min.length() - i; j++) {
tmp = min.substring(j, j + i);
// 遍历取出最长字符串中所有可能出现的子串
for (int k = 0; k <= max.length() - i; k++) {
if (max.substring(k, k + i).equals(tmp)) {
if (tmp.length() > len) {
flag = 0;
arr1[flag++] = k;
len = tmp.length();
} else if (tmp.length() == len) {
arr1[flag++] = k;
}
}
}
}
}
System.out.println("相同的字符串为:");
for (int i = 0; i < flag; i++) {
System.out.println(max.substring(arr1[i], len + arr1[i]));
}
}
不知道是不是你要的,是的话,望采纳。不是的话可以参考参考
string Test = “This is test for string”; int i =test.indexOf("This");//i=0 i表示包含的字符串起始位置 0为从第一位开始。简单明了
使用indexOf(String s),如果包含,返回的值是包含该子字符串在父类字符串中起始位置;如果不包含必定全部返回值为-1
String a = "asdf";
String b = "s";
System.out.println(a.indexOf(b));
如果包含 则返回值不为-1,如果不包含 返回值为-1