Search code examples
javastringstartswithends-with

Compare two strings in java, how to print equals words


In java I got 2 strings (each contains a list of words for example ab,ac,ad,bb,bc,bd and second string which contains user input (for example word "a") I want to compare those 2 strings and get text that first string contain (like if startswith return true I want to print out word that matches for example in my case ab,ac,ad) anyone know how can I do it ?


Solution

  • Use split and iterate

    String input = "a";
    String str = "ab,ac,ad,bb,bc,bd";
    for (String s: str.split(",")) {
        if (s.startsWith(input)) {
            System.out.println("String " + s + " starts with " + input);
        }
    }