How to check if second string is subsequence of first string in Java

1 Answer

0 votes
public class Program {
    public static boolean isSecondStringSubsequenceOfFirstString(String first, String second) {
        int i = 0, j = 0;
        
        while (i < first.length()) {
            if (j >= second.length()) {
                return false;
            }
            if (first.charAt(i) == second.charAt(j)) {
                System.out.print("first.charAt(i) = " + first.charAt(i) + " second.charAt(j) = " + second.charAt(j));
                System.out.println(" i = " + i + " j = " + j);
                i++;
            }
            j++;
        }
        
        return true;
    }
    
    public static void main(String[] args) {
        String first = "java programming";
        String second = "javascript programming";
        
        System.out.println(isSecondStringSubsequenceOfFirstString(first, second) ? "yes" : "no");
    }
}




/*
run:

first.charAt(i) = j second.charAt(j) = j i = 0 j = 0
first.charAt(i) = a second.charAt(j) = a i = 1 j = 1
first.charAt(i) = v second.charAt(j) = v i = 2 j = 2
first.charAt(i) = a second.charAt(j) = a i = 3 j = 3
first.charAt(i) =   second.charAt(j) =   i = 4 j = 10
first.charAt(i) = p second.charAt(j) = p i = 5 j = 11
first.charAt(i) = r second.charAt(j) = r i = 6 j = 12
first.charAt(i) = o second.charAt(j) = o i = 7 j = 13
first.charAt(i) = g second.charAt(j) = g i = 8 j = 14
first.charAt(i) = r second.charAt(j) = r i = 9 j = 15
first.charAt(i) = a second.charAt(j) = a i = 10 j = 16
first.charAt(i) = m second.charAt(j) = m i = 11 j = 17
first.charAt(i) = m second.charAt(j) = m i = 12 j = 18
first.charAt(i) = i second.charAt(j) = i i = 13 j = 19
first.charAt(i) = n second.charAt(j) = n i = 14 j = 20
first.charAt(i) = g second.charAt(j) = g i = 15 j = 21
yes

*/

 



answered Mar 24, 2024 by avibootz

Related questions

...