如何在Java中判断一个字符串是否为另一个字符串的子串

7

你好,我需要计算一个给定的字符串是否是另一个更大的字符串的子串。 例如:

String str = "Hallo my world";
String substr = "my"

方法“contains”应该返回true,因为str包含substr(否则返回false)。

我在String类中寻找类似“contains”的方法,但没有找到。我想唯一的解决方案是使用模式匹配。如果是这种情况,哪种方法更好(更便宜)呢?

谢谢!


3
答案是 str.indexOf(substr) != -1 - biziclop
太多正确的答案在这么短的时间内出现了,非常感谢大家。你们节省了我很多时间。我正在使用Java 1.5,并且我一直在查看Java 1.4.2的文档,因此我没有意识到存在“contains”方法。子索引方法也可以。给你们点赞。 - Luixv
@biziclop,如果你错过了,你需要在下面的答案部分发布答案。 - dogbane
@dogbane 我可以,但我不一定要这样做。 :) - biziclop
16个回答

24

Java 1.5引入了一个名为contains()的方法。如果你使用的是早期版本,那么很容易用下面的方法替换它:

str.indexOf(substr) != -1

5
 String str="hello world";
        System.out.println(str.contains("world"));//true
        System.out.println(str.contains("world1"));//false

(该段内容为HTML代码,无法直接翻译。)

3
  String s = "AJAYkumarReddy";
    String sub = "kumar";
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == sub.charAt(count)) {
            count++;
        } else {
            count = 0;
        }
        if (count == sub.length()) {
            System.out.println("Sub String");
            return;
        }

    }

你的算法不够优化。不要重复造轮子,看看被接受的答案。 - Luixv
1
对于以下代码,将会失败: String s = "aabcxbx"; String sub = "abc"; - shivarajan

2

1
这是一个通用的方法,您可以使用它。
public static boolean isSubstring(String s1, String s2) {
    if(s1.length() == s2.length()) 
        return s1.equals(s2);
    else if(s1.length() > s2.length())
        return s1.contains(s2);
    else
        return s2.contains(s1);

}

你的算法不够优化。不要重复造轮子,看看被接受的答案。 - Luixv

1

1
    public boolean isSubString(String smallStr, String largerStr) {
    char[] larger = largerStr.toCharArray();
    char[] smaller = smallStr.toCharArray();

    int i = 0;

    for (int j = 0; j < larger.length; j++) {
        if(larger[j] == smaller[i]){
            if(i == smaller.length -1){
                //done we found that this string is substring
                return true;
            }
            i++;
            continue;
        }else{
            if(i > 0){
                //that means we encountered a duplicate character before and if string was substring 
                // it shouldn't have hit this condition..
                if(larger.length - j >= smaller.length){
                    i = 0;
                    //reset i here because there are still more characters to check for substring..
                }else{
                    //we don't have enough characters to check for substring.. so done..
                    return false;
                }

            }
        }

    }

    return false;
}

1
if (str.indexOf(substr) >= 0) {
    // do something
}

将在 str="foobar"substr="foo" 上失败,因为 indexOf() 将返回 0 - Joachim Sauer

1

String.indexOf(substr) 的时间复杂度为 O(n2)。Luixv 寻求一种更便宜的解决方案。但据我所知,目前没有比现有算法更好的算法。


0
你可以使用.substring(int beginIndex,int lastIndex)来检查这个程序。示例代码如下:
public class Test {

    public static void main(final String[] args) {
        System.out.println("Enter the first String");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        try {
            String s1 = br.readLine();
            System.out.println("Enter the second String");
            String s2 = br.readLine();

            boolean result = isSubStr(s1, s2);
            if (result == true)
                System.out.println("The second String is substring of the first String");
            else
                System.out.println("The second String is not a substring of the first String");

        } catch (IOException e) {
            System.out.println("Exception Caught: " + e);
        }

    }

    public static boolean isSubStr(String st1, String s2) {

        boolean result = false;

        String tem_str = "";
        int len1 = st1.length();
        int i = 0;
        int j;

        while (i < len1) {
            j = i+1;
            while (j <=len1) {
                tem_str = st1.substring(i, j);
                if (tem_str.equalsIgnoreCase(s2)) {
                    result = true;
                    break;
                }
               j++;
            }

            i++;
        }
        return result;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接