Can I execute a Java method for finding the substring of a string?

263    Asked by CelinaLagunas in Java , Asked on Jan 12, 2024

 I am currently working on an application that is related to the text process in which users can input their sentences, and the program needs to verify if a particular substring exists in those sentences of the users or not. For this specific purpose, I need to execute a Java method that can check the substrings. My code should look like this:-

Public class SubstringChecker {
    Public static boolean containsSubstring(String mainString, String subString) {
        // Your implementation here
        
    }
    Public static void main(String[] args) {
        String text = “This is a sample text to check if substring exists.”;
        String wordToCheck = “sample”;
        Boolean isSubstring = containsSubstring(text, wordToCheck);
        System.out.println(“Does the text contain the word ‘sample’? “ + isSubstring);
    }
}
Answered by Daniel Cameron

In the context of Java programming language, you can check if string contain substring or not by using the method of “ contains()” or even the method of “indexOf()”. Here is the example given of how you can implement the “containsSubstring” method for your particular objective:-

Public class SubstringChecker {
    Public static boolean containsSubstring(String mainString, String subString) {
        Return mainString.contains(subString);
        // Alternatively, you can use indexOf method:
        // return mainString.indexOf(subString) != -1;
    }
    Public static void main(String[] args) {
        String text = “This is a sample text to check if substring exists.”;
        String wordToCheck = “sample”;
        Boolean isSubstring = containsSubstring(text, wordToCheck);
        System.out.println(“Does the text contain the word ‘sample’? “ + isSubstring);
    }
}

In this above code the “containsSubstring” method would use the “contains()” method for ensuring or checking if “mainstring” contains “substrings” or not. If the substring would be found the result would be provided in the form of “true”, however, if there would be no substring of the string then the result would be “false”.



Your Answer

Interviews

Parent Categories