Finding index position of a second string in a first string.


How to find the position of a second string from first sting?. I have a main string and want to find the second string is existed or not,position along with the index of the starting point of second string. Finding out index position of a second string in a first string.

Overview on - Finding index position of a second string in a first string


Open the Microsoft Visual Studio 2010 and select the Console application and implement the below code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//To enter the first string
Console.WriteLine("Please select first string");
string firstStr = Console.ReadLine();
//To enter the second string
Console.WriteLine("Please select second string");
string secondStr = Console.ReadLine();
//Find the length of first string and subtract from the second and loop it
for (int loop = 0; loop <= firstStr.Length - secondStr.Length; loop++)
{
bool flag = true;
//looping the second string.
for (int innerLoop = 0; innerLoop < secondStr.Length; innerLoop++)
{
//comparing the values from first sting and second one.
if (firstStr[loop + innerLoop] == secondStr[innerLoop])
{
flag = flag && true;
}
else
{
flag = flag && false;
}
}
if (flag)
{
Console.WriteLine(loop.ToString());
}
}
Console.ReadLine();

}
}
}




Steps to do this:

1)enter the first string and read it.
2) enter the second string and read it.
3)Find the length of first string and subtract from the second and loop it
4)Declare the boolean value and looping the second string.
5)comparing the values from first sting and second one.
6) Now Write the Index.

Regards,
Naveen


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: