Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract substring from a string until finds a comma

Tags:

I'm building a page and would like to know how to extract substring from a string until finds a comma in ASP.Net C#. Can someone help please?

like image 361
alina Avatar asked Sep 26 '09 08:09

alina


2 Answers

substring = str.Split(',')[0];

If str doesn't contain any commas, substring will be the same as str.

EDIT: as with most things, performance of this will vary for edge cases. If there are lots and lots of commas, this will create lots of String instances on the heap that won't be used. If it is a 5000 character string with a comma near the start, the IndexOf+Substring method will perform much better. However, for reasonably small strings this method will work fine.

like image 82
thecoop Avatar answered Oct 13 '22 00:10

thecoop


var firstPart = str.Split(new [] { ',' }, 2)[0]

Second parameter tells maximum number of parts. Specifying 2 ensures performance is fine even if there are lots and lots of commas.

like image 21
Konstantin Spirin Avatar answered Oct 13 '22 01:10

Konstantin Spirin