Tip 10 : Returning the first part of a string with delimiter

You have a string delimited by underscore such as 1stPart_2ndPart_3rdPart and want to return the first part of the string only.

C# Implementation of using Split function:

T-SQL implementation of using SUBSTRING and CHARINDEX functions:

 

Published Monday, February 08, 2010 8:45 PM by StanleyGu
Filed under: , ,

Comments

# re: Tip 10 : Returning the first part of a string with delimiter

Tuesday, February 09, 2010 3:04 AM by Petar Petrov

Hi. Your .NET solution isn't very efficient. The split method will probably create a large array(depending on the input) and you will use only the first element. What a waste ;) Here's more efficient and robust solution :

var input = @"1stPart_2ndPart_3rdPart";

var firstPart = string.Empty;

var index = input.IndexOf("_");

if (index >= 0)

{

firstPart = input.Substring(0, index);

}

Leave a Comment

(required) 
(required) 
(optional)
(required)