Java中如何知道给定字符串是否是另一个字符串的子字符串

发布于 2024-10-14 01:46:19 字数 279 浏览 5 评论 0原文

你好 我必须计算给定的字符串是否是更大字符串的子字符串。 例如,

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

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

我在 String 类中寻找类似“包含”的内容 但我没有找到。我认为唯一的解决方案是使用 模式匹配。如果是这种情况,这将是更好(最便宜)的方法 要这样做吗?

谢谢!

Hi
I have to compute if a given string is substring of a bigger string.
For example

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

The method "contains" should return true because str contains substr (false otherwise).

I was looking for something like "contains" at the String class
but I didn't find it. I suppose that the only solution is to use
pattern matching. If this is the case which would be the better (cheapest) way
to do this?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

倾其所爱 2024-10-21 01:46:19

您可以使用 .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;
    }
}

You can use .substring(int beginIndex,int lastIndex) to check this program. Sample code goes as below:-

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;
    }
}
宣告ˉ结束 2024-10-21 01:46:19

使用indexOf,如果没有匹配,它将返回-1(contains是在1.5中添加的,也许您使用的是较旧的jdk?)请参阅JDK 1.4.2 中 String 类中的“contains(CharSequence s)”方法了解详细信息

use indexOf it will return -1 if no match (contains was added in 1.5, maybe you are using older jdk?) see "contains(CharSequence s)" method in String class in JDK 1.4.2 for details

你如我软肋 2024-10-21 01:46:19
  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;
        }

    }
  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;
        }

    }
感受沵的脚步 2024-10-21 01:46:19

一个contains() 方法!它是在 Java 1.5 中引入的。如果您使用的是早期版本,那么很容易将其替换为:

str.indexOf(substr) != -1

There is a contains() method! It was introduced in Java 1.5. If you are using an earlier version, then it's easy to replace it with this:

str.indexOf(substr) != -1
我不咬妳我踢妳 2024-10-21 01:46:19
 String str="hello world";
        System.out.println(str.contains("world"));//true
        System.out.println(str.contains("world1"));//false
 String str="hello world";
        System.out.println(str.contains("world"));//true
        System.out.println(str.contains("world1"));//false
萌化 2024-10-21 01:46:19

这是您可以使用的通用方法

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);

}

here is a general method that you can use

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);

}
孤独患者 2024-10-21 01:46:19
public static boolean isSubstring(String s1, String s2){
    if(s1.length()<s2.length()) return false;
    if(s1.length()==s2.length()) return s1.equals(s2);
    for(int i=0;i<=s1.length()-s2.length();i++){
        if(s1.charAt(i)==s2.charAt(0)){
            int matchLength=1;
            for(int j=1;j<s2.length();j++){
                if(s1.charAt(i+j)!=s2.charAt(j)){
                    break;
                }
                matchLength++;
            }
            if(matchLength==s2.length()) return true;
        }
    }
    return false;
}

这将检查 s2 是否是 s1 的子字符串。

public static boolean isSubstring(String s1, String s2){
    if(s1.length()<s2.length()) return false;
    if(s1.length()==s2.length()) return s1.equals(s2);
    for(int i=0;i<=s1.length()-s2.length();i++){
        if(s1.charAt(i)==s2.charAt(0)){
            int matchLength=1;
            for(int j=1;j<s2.length();j++){
                if(s1.charAt(i+j)!=s2.charAt(j)){
                    break;
                }
                matchLength++;
            }
            if(matchLength==s2.length()) return true;
        }
    }
    return false;
}

This checks if s2 is a substring of s1.

感性 2024-10-21 01:46:19

我认为有一个 String 函数可以满足您的要求:String.indexOf(String)。

请参阅此链接: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)

那么,你可以编写这个函数:

public boolean isSubstring(String super, String sub) {
    return super.indexOf(sub) >= 0;
}

I think there is a String function that does just what you are asking: String.indexOf(String).

See this link: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)

So, then you could write this function:

public boolean isSubstring(String super, String sub) {
    return super.indexOf(sub) >= 0;
}
尝蛊 2024-10-21 01:46:19

String.indexOf(substr) 复杂度是 O(n2) .. Luixv 提出了一种更便宜的解决方案.. 但就 而言,我知道没有比当前算法更好的算法了。

String.indexOf(substr) complexity is O(n2).. Luixv asked a cheaper solution.. But as far as , I know there is no better algorithm than current one.

葬シ愛 2024-10-21 01:46:19
    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;
}
    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;
}
财迷小姐 2024-10-21 01:46:19
if (str.indexOf(substr) >= 0) {
    // do something
}
if (str.indexOf(substr) >= 0) {
    // do something
}
你如我软肋 2024-10-21 01:46:19

通过这个方法。
访问棘手的代码

public static boolean isSubString(String s, String sub) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == sub.charAt(count)) {
            count++;
        } else {
            i-=count;
            count = 0;
        }
        if (count == sub.length()) {
            return true;
        }

    }
    return false;
}

Go through this method.
visit for tricky code

public static boolean isSubString(String s, String sub) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == sub.charAt(count)) {
            count++;
        } else {
            i-=count;
            count = 0;
        }
        if (count == sub.length()) {
            return true;
        }

    }
    return false;
}
﹏雨一样淡蓝的深情 2024-10-21 01:46:19
public class StringIsSubString {

    public static void main(String[] args) {

        String s1 = "wel";
        String s2 = "12wlecome123";

        boolean isSubStr = isSubStr(s1,s2);
        System.out.println(isSubStr);
    }

    private static boolean isSubStr(String s1, String s2) {
        String s3 = "";
        int j = 0;

        if(s1.length() > s2.length()) {
            return false;
        } else if(s1.equals(s2)){
            return true;
        } else {
            for(int i=0; i<s1.length();i++) {
                for(; j<s2.length();j++) {
                    if(s1.charAt(i) == s2.charAt(j)) {
                        s3 = s3 + s1.charAt(i);
                        break;
                    }
                }
            }
            if(s3.equals(s1)) {
                return true;
            }
            return false;       
        }
    }
}
public class StringIsSubString {

    public static void main(String[] args) {

        String s1 = "wel";
        String s2 = "12wlecome123";

        boolean isSubStr = isSubStr(s1,s2);
        System.out.println(isSubStr);
    }

    private static boolean isSubStr(String s1, String s2) {
        String s3 = "";
        int j = 0;

        if(s1.length() > s2.length()) {
            return false;
        } else if(s1.equals(s2)){
            return true;
        } else {
            for(int i=0; i<s1.length();i++) {
                for(; j<s2.length();j++) {
                    if(s1.charAt(i) == s2.charAt(j)) {
                        s3 = s3 + s1.charAt(i);
                        break;
                    }
                }
            }
            if(s3.equals(s1)) {
                return true;
            }
            return false;       
        }
    }
}
歌枕肩 2024-10-21 01:46:19

*它们中的任何子字符串都将以子字符串的第1位的形式进行计数*

int isSubstring(string s1, string s2) {
    int M = s1.length();
    int N = s2.length();

    for (int i = 0; i <= N - M; i++) {
        int j;
        for (j = 0; j < M; j++)
            if (s2[i + j] != s1[j])
                break;

        if (j == M)
            return i;
    }

    return -1;
}


int main() {
    string s1 = "kumar";
    string s2 = "abhimanyukumarroy";
    int res = isSubstring(s1, s2);
    if (res == -1)
        cout << "Not present";
    else
        cout << "Present at index " << res;
    return 0;
}

*In their any sub string will be count by the form of 1th place of string of substring *

int isSubstring(string s1, string s2) {
    int M = s1.length();
    int N = s2.length();

    for (int i = 0; i <= N - M; i++) {
        int j;
        for (j = 0; j < M; j++)
            if (s2[i + j] != s1[j])
                break;

        if (j == M)
            return i;
    }

    return -1;
}


int main() {
    string s1 = "kumar";
    string s2 = "abhimanyukumarroy";
    int res = isSubstring(s1, s2);
    if (res == -1)
        cout << "Not present";
    else
        cout << "Present at index " << res;
    return 0;
}
少女净妖师 2024-10-21 01:46:19
    String str1 = "Java8 makes Java more powerful";
    String str2 = "Java";
    char c;
    char d;
    int count=0;
    boolean match = true;
    for (int i = 0; i < str1.length(); i++) {
        c = str1.charAt(i);
        for (int j = 0; j < str2.length(); j++) {
            d = str2.charAt(j);
            if (c == d) {
                match = true;
                count++;
                if(count== str2.length()){
                    i = str1.length();
                    break;
                }
                i++;
                c = str1.charAt(i);
            } else {
                match = false;
            }   
        }
    }

    if(match == true){
        System.out.println("SubString ");
    }
    String str1 = "Java8 makes Java more powerful";
    String str2 = "Java";
    char c;
    char d;
    int count=0;
    boolean match = true;
    for (int i = 0; i < str1.length(); i++) {
        c = str1.charAt(i);
        for (int j = 0; j < str2.length(); j++) {
            d = str2.charAt(j);
            if (c == d) {
                match = true;
                count++;
                if(count== str2.length()){
                    i = str1.length();
                    break;
                }
                i++;
                c = str1.charAt(i);
            } else {
                match = false;
            }   
        }
    }

    if(match == true){
        System.out.println("SubString ");
    }
燕归巢 2024-10-21 01:46:19

考虑以下代码:

如果子字符串存在,则返回给定字符串中子字符串的起始索引

否则返回-1

public static int isSubstring(String str, String pattern)
{
    int str_length = str.length();
    int pattern_length = pattern.length();

    for (int i = 0; i <= str_length - pattern_length; i++)
    {
        int j;

        for (j = 0; j < pattern_length; j++)
            if (str.charAt(i + j) != pattern.charAt(j))
                break;

        if (j == pattern_length)
            return i;
    }
    return -1;
}

Consider the following code:

If substring is present then it returns the start index of substring in a given string

Else returns -1

public static int isSubstring(String str, String pattern)
{
    int str_length = str.length();
    int pattern_length = pattern.length();

    for (int i = 0; i <= str_length - pattern_length; i++)
    {
        int j;

        for (j = 0; j < pattern_length; j++)
            if (str.charAt(i + j) != pattern.charAt(j))
                break;

        if (j == pattern_length)
            return i;
    }
    return -1;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文