Introduction
A program that will get a string and match it with a substring.
Usually when a programmer goes to an interview, the company asks to write the code of some program to check your logic and coding abilities.
You can write the code in any language, like C, C++, Java, C# and so on. There is no required language and technology because the company wants to check your ability to think and your skills to write the code.
Some companies only want the algorithm to check your skills.
One of the programs in those common programs is the following.
Question
You are given an input string, string1. Write a function to find whether string1 contains all the characters of the word “nagarro” in the same order as they appear in “nagarro”. The function will be true if the input string1 contains all the letters in the same order and false otherwise.
For example:
Input- string1= “nbacgddardsardo”
Output: True (explanation: “nbacgddardsardo”)
Input- string1= “anagarorpa”
Output: False (explanation: “anagarorpa”)
Input- string1= “nagarro01”
Output: True (explanation: “nagarro01”)
To do this, I will use Visual Studio 2012 as an IDE and C# as the language.
Create a new console application named "ConsoleApplication1".
Where you will get the page that will look like:
I will now provide the procedure for creating the code.
- Add the code in the main() method to get some inputs from the user.
- Get the string
- Get the sub string to match
- static void Main(string[] args)
- {
-
- Console.Write("Eneter the string:");
- string input = Console.ReadLine();
-
-
- Console.Write("Eneter the sub string:");
- string match = Console.ReadLine();
- }
- Write the code in a function to match the sub-string within the input string and return True/False.
- private static bool substr(string input, string match)
- {
-
- string temp = "";
-
- for (int i = 0, k = 0; i < input.Length; i++)
- {
-
- if (input[i] == match[k])
- {
-
- temp += input[i];
- k++;
- }
-
- if (k == match.Length) break;
- }
-
- return match.Equals(temp);
- }
- Call the function with the 2 parameters, array and sum, from the main() method.
- Console.WriteLine("Output String is:");
-
- Console.WriteLine(substr(input, match).ToString());
- Console.ReadKey();
Result
- If I provide ”nbacgddardsardo” as the string and “nagarro” as the sub-string then the output will be:
Output: True
- If I provide ”anagarorpa” as the string and “nagarro” as the sub-string then the output will be like:
Output: False
- If I provide ”nagarro01” as the string and “nagarro” as the sub-string then the output will be like:
Output: True