Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting first token from a delimeted string

Tags:

string

c#

i have a string: e.g. WORD1_WORD2_WORD3

how do i get just WORD1 from the string? i.e the text before the first underscore

like image 452
raklos Avatar asked Jun 09 '09 11:06

raklos


People also ask

How do I split just the first instance?

We can split over only the first occurrence of the delimiter using slice() and join() . slice(1) will remove the first element of the array.

How do I extract the first word of a string?

Extract the First Word Using Text Formulas The FIND part of the formula is used to find the position of the space character in the text string. When the formula finds the position of the space character, the LEFT function is used to extract all the characters before that first space character in the text string.

How do you split the first character of a string?

Use the String. split() method with array destructuring to split a string only on the first occurrence of a character, e.g. const [first, ... rest] = str.


2 Answers

It may be tempting to say Split - but that involves the creating of an array and lots of individual strings. IMO, the optimal way here is to find the first underscore, and take a substring:

string b = s.Substring(0, s.IndexOf('_')); // assumes at least one _

(edit)

If you are doing this lots, you could add some extension methods:

public static string SubstringBefore(this string s, char value) {
    if(string.IsNullOrEmpty(s)) return s;
    int i = s.IndexOf(value);
    return i > 0 ? s.Substring(0,i) : s;
}
public static string SubstringAfter(this string s, char value) {
    if (string.IsNullOrEmpty(s)) return s;
    int i = s.IndexOf(value);
    return i >= 0 ? s.Substring(i + 1) : s;
}

then:

string s = "a_b_c";
string b = s.SubstringBefore('_'), c = s.SubstringAfter('_');
like image 194
Marc Gravell Avatar answered Oct 04 '22 16:10

Marc Gravell


YOUR_STRING.Split('_')[0]

In fact the Split method returns an array of strings resulting from splitting the original string at any occurrence of the specified character(s), not including the character at which the split was performed.

like image 44
em70 Avatar answered Oct 04 '22 15:10

em70