Ad

Sunday, August 4, 2013

Split Method In String Class using C#.Net?

Overview:
                 In this article i would like to publish Split Method In String Class using C#.Net.Related to String related articles you can visit the link.



Description:
                    String is a collection of characters it can be used as a string data type as well as string class.When string acts as a class it consists of split method.

Split:
        String class consists of split method it is used to split a data as per the usage of delimiters used by a users.It identifies the substrings that are delimited by one or more characters specified in an array, and then return these substrings in a string array.

Forms of a Split Method:
  • string[] Split(params char[])
  • string[] Split(params char[] separator) 
Example:
             we want to split a given string "Naga Veerendra Parvataneni".Here we use " "(space) as a delimiter like wise we can split a given strings.

In this section i would like to explore different ways of splitting a given string

Program:



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

namespace split123
{
    class Class1
    {
        static void Main(string[] args)
        {
            //Strings here i will partion with space,comma,partof astring,\n
            string e1 = "Naga Veerendra Parvataneni";
            char[] a = new char[] { ' ' };
            string[] finalstring;
            Console.WriteLine("Original String Before Split Method:"+e1);
            finalstring = e1.Split(a);
            Console.WriteLine("After Split Method");
            foreach (string ss in finalstring)
            {
                Console.WriteLine(ss);
            }
            Console.WriteLine("*************************************");
            string e2 = "P,Naga,Veerendra";
            Console.WriteLine("Original String Before Split Method:" + e2);
            char[] b = new char[] { ',' };
            finalstring = e2.Split(b);
            foreach (string ss in finalstring)
            {
                Console.WriteLine(ss);
            }
            Console.WriteLine("*************************************");
            string e3 = "PMMMNaMMMgaMMMVeerMMMendra";
            Console.WriteLine("Original String Before Split Method:" + e3);
            string[] c = new string[] { "MMM" };
            finalstring = e3.Split(c,StringSplitOptions.None);
            foreach (string ss in finalstring)
            {
                Console.WriteLine(ss);
            }
            Console.ReadLine();
        }
    }
}

 Output:
Split

Note:
         Don't use unrecognized delimiters in split array.Like "\N" is Different from "\n".If you use that it gives an error.It Can be Possible only if you use "@" preceded of the string.For Example U can visit.

No comments: