How to check if second string is subsequence of first string in C#

1 Answer

0 votes
using System;

public class Program
{
	public static bool isSecondStringSubsequenceOfFirstString(string first, string second) {
		int i = 0, j = 0;

		while (i < first.Length) {
			if (j >= second.Length) {
				return false;
			}
			if (first[i] == second[j]) {
				Console.Write("first[i] = " + first[i] + " second[j] = " + second[j]);
				Console.WriteLine(" i = " + i + " j = " + j);
				i++;
			}
			j++;
		}

		return true;
	}

	public static void Main(string[] args)
	{
		string first = "c# programming";
		string second = "c# pro programming";

		Console.WriteLine(isSecondStringSubsequenceOfFirstString(first, second) ? "yes" : "no");
	}
}



/*
run:

first[i] = c second[j] = c i = 0 j = 0
first[i] = # second[j] = # i = 1 j = 1
first[i] =   second[j] =   i = 2 j = 2
first[i] = p second[j] = p i = 3 j = 3
first[i] = r second[j] = r i = 4 j = 4
first[i] = o second[j] = o i = 5 j = 5
first[i] = g second[j] = g i = 6 j = 10
first[i] = r second[j] = r i = 7 j = 11
first[i] = a second[j] = a i = 8 j = 12
first[i] = m second[j] = m i = 9 j = 13
first[i] = m second[j] = m i = 10 j = 14
first[i] = i second[j] = i i = 11 j = 15
first[i] = n second[j] = n i = 12 j = 16
first[i] = g second[j] = g i = 13 j = 17
yes

*/

 



answered Mar 24, 2024 by avibootz

Related questions

...