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:

 

2 Comments

  • 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);
    }

  • I benefit reading it. I have need of to learn more on this subject.. Thanks for the sake writing this extraordinary post.. Anyway, I am gonna subscribe to your support and I wish you mail again soon.

Comments have been disabled for this content.