Follow by Email

Sunday, June 9, 2013

Using 'Indexof' and 'Substring' keywords in asp.net | String Methods 'IndexOf' and 'SubString' | IndexOf and Substring Example,


Hello in this post i will show the uses of  'IndexOf' and 'Substring' in asp.net

1. IndexOf : 

IndexOf provides the position of the Element or word.

if we have a string "Hello World" and we want know at what position
the "world" string starts.
'IndexOf' keyword will give the output as 6. So at 6th position the World word starts.

Syntax:

int i1;
i1 = s.IndexOf("World");

//output
//6


2. SubString:

Suppose we have a string like 'My Name is Alex Ferguson'. And from this string
i want only Alex word. Then here we can use Substring.

string s = "My Name is Alex Ferguson";
string s1 = s.Substring(12, 4);

//output
//Alex

Example:


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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int i1,i2;
            string s1;
            string s = "Hello World";

            i1 = s.IndexOf("World");
            s1 = s.Substring(0, 5);
            i2 = s.Substring(0, 5).IndexOf("o");

            Console.WriteLine("Entered String: "+s);
            Console.WriteLine("\nPosition of 'World': "+i1);
            Console.WriteLine("\nSubString: " + s1);
            Console.WriteLine("\nPosition of 'o' in the Substring: " + i2);
            Console.ReadLine();
        }
    }
}


Result :