Share via

Best way to split a string

swodniW 141 Reputation points
2021-07-06T15:55:18.983+00:00

Hello,
what's the best way to split a string to obtain the second substring(divided using ':')?
I know how to do it using byte num=0; string[] array = tosplitstring.Split(':'); foreach(string substring in array) {num++; if(num==2){string secondelement=substring;} ``}
I am quite sure this method is not the best. Thanks in advance

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

Karen Payne MVP 35,606 Reputation points Volunteer Moderator
2021-07-06T16:25:24.44+00:00

It's wise to use assertion e.g.

string tosplitstring = "first:second:third";
var split = tosplitstring.Split(':');

if (split.Length >1)
{
    var indexToFind = 2;
    var items = split.Select((value, index) => new {Value = value, Index = index}).ToList();
    var result = items.FirstOrDefault(x => x.Index == indexToFind);
    Debug.WriteLine(result is not null ? result.Value : $"Failed to find {indexToFind}");
}

Was this answer helpful?

2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.