views:

138

answers:

5
+2  Q: 

string splitting

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

+7  A: 
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.

emaster70
As Mark pointed out, this is a very inefficient way of doing this.
Philippe Leybaert
It's just the most straightforward way to do this, the most intuitive and unless the application is performance-critical and repeats that operation over and over again it won't really matter. Anyway I agree that's not the solution with the lowest execution time :)
emaster70
make sure to add some validation, that there is actual a '_' in the string, if you do it dynamically later :-)
Peter Gfader
+1  A: 

("WORD1_WORD2_WORD3").Split('_')[0]

should return "WORD1". If it doesn't work try .Spilt() on a string variable with the Content you specified.

string str="WORD1_WORD2_WORD3";
string result=str.Split('_')[0];

This actually returns an array:

{"WORD1", "WORD2", "WORD3"}
wsd
You don't need the brackets around the string, you can just do "".Split('_')[0];
Slace
A: 

There are several ways. You can use Split, Substring. etc. An example with Split:

String var = "WORD1_WORD2_WORD3";

String result = var.Split('_')[0];

fbinder
+10  A: 

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('_');
Marc Gravell
good thing you added your comment :)
Philippe Leybaert
+6  A: 

if s is the string:

int idx = s.IndexOf('_');

if (idx >= 0)
  firstPart = s.Substring(0,idx);
Philippe Leybaert
+1 because we don't have the problems that .Split() can cause
Peter Gfader