String program #11 (Check
whether a string is contained in other string)
Enter string1: This is my eLearning
website www.imaginationhunt.com
Enter searched string: imaginationhunt
String1 contain searched string
The program for the string is written
in C# programming language and will accept two strings as input. The logic is
to check whether String1 contain searched string. There are two ways to check:
1.
Using
in-built function “Contains”
2.
Using
for loop
Let’s find out a simple and easy way
to code the program.
Practical Implementation:
using System;
namespace patternProblem.String
{
class String11 //check whether a string is contained in other string
{
static void Main(string[] args)
{
Console.Write("Enter string1: ");
string str1 = Console.ReadLine();
Console.Write("Enter searched string: ");
string str2 = Console.ReadLine();
//Method-1 (Using in-built Contains property)
if
(str1.Contains(str2))
{
Console.WriteLine("String1 contain searched
string");
}
else
{
Console.WriteLine("String1 doesnot contain searched
string");
}
//Method-2 (Using for loop)
int
m = str1.Length;
int
n = str2.Length;
char[]
ch1 = str1.ToCharArray();
char[]
ch2 = str2.ToCharArray();
String11 objStr11 = new String11();
string strOutput = objStr11.isSubSequence(ch1, ch2, m, n) ? "String1 contain
searched string "
: "String1
doesnot contain searched string";
Console.WriteLine(strOutput);
Console.ReadKey();
}
// Returns true if
str1[] is a subsequence of str2[]. m is
// length of str1
and n is length of str2
bool isSubSequence(char[] str1, char[] str2, int m, int n)
{
int
j = 0; // For index of str1
(or subsequence
// Traverse str2 and str1, and compare current character
// of str2 with first unmatched char of str1, if matched
// then move ahead in str1
for
(int i = 0; i < m && j
< n; i++)
{
if (str1[i] == str2[j])
{
j++;
}
}
// If all characters of str1 were found in str2
return (j == n);
}
}
}
Output:
The input
string1 here is “This is my eLearning website www.imaginationhunt.com” and searched
string is “imaginationhunt”. So, based on the input, program will check whether
string1 contain searched string. The output is shown below:
Enter string1: This is my eLearning website
www.imaginationhunt.com
Enter searched string: imaginationhunt
String1 contain searched string
String1 contain searched string
Press any key to continue . . .
For any
query, comment us below.
Skip to
Main Table String based program
Keep learning and sharing...
No comments:
Post a Comment