Resources » .NET programming » .NET Framework

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


Posted Date: 08-Jan-2012  Last Updated:   Category: .NET Framework    
Author: Member Level: Gold    Points: 8


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


Did you like this resource? Share it with your friends and show your love!

Responses to "Finding index position of a second string in a first string."

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

Feedbacks      

Post 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:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Pawan Awasthi
    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India