ARTICLE

Substring in C#

Posted by Mahesh Chand Articles | String in C# August 22, 2010
How to get a substring from a string in C#.
Reader Level:

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();

 

Login to add your contents and source code to this article
post comment
     
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts