Search code examples
javastringwords

Word in a word java


SO my problem is that i have a string and i need to search in that string if it is another string. Basically i just want to search if lets say "ala" exists in "balama". I thought about Search by letter by letter but its consuming and if exists more than 2 or 3 words i can't do it. Any suggestions or there is a method in the string? I saw the CompareTO method but doesn't seem to work on partial words in a string. Just the idea to get me started. Thank you for you'r time and consideration.


Solution

  • The String method you are looking for is called indexOf:

    String testStr = "Vlad Adrian";
    
            String substr = "ad";
    
            int pstn = testStr.indexOf(substr);
    
            System.out.println(substr + " position in " + testStr + " is " + pstn);
    

    Prints

    ad position in Vlad Adrian is 2
    

    If the substring is not found, the method returns -1