Substring in C#


String.Substring method retrieves a substring from a string. If you do not specify any parameters in this method, it will retrieve first sub string. You can also specify the starting index and number of characters in a substring you want to retrieve.

The following code snippet gets a string starting at index 0 (first character) to next 12 characters in a string. If a string has less than 12 characters, you will see an exception.

string authorsString = "Mahesh Chand, Mike Gold, Raj Beniwal, Praveen Kumar";

  

// Get a substring strating at 0th index to next 12 characters

string mahesh = authorsString.Substring(0, 12);

Console.WriteLine(mahesh);

 

// Get all substrings separated by Space

char[] commaSeparator = new char[] { ',' };

string[] authors = authorsString.Split(commaSeparator, StringSplitOptions.None);

foreach (string author in authors)      

{

    Console.WriteLine(author);

}

Console.ReadKey();

 

Up Next
    Ebook Download
    View all
    Learn
    View all