Extract first token from delimeted string

I have a line: for example WORD1_WORD2_WORD3

How can I get only WORD1 from a string? those. text before the first underline

+4
source share
5 answers
 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 in which the split was performed.

+9
source

It may be tempting to say Split - but this has to do with creating an array and many separate lines. IMO, the best way here is to search for the first underscore and take a substring:

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

(edit)

If you are doing this lot, you can 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('_'); 
+10
source

if s is a string:

 int idx = s.IndexOf('_'); if (idx >= 0) firstPart = s.Substring(0,idx); 
+7
source

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

should return "WORD1". If it doesn't work, try .Spilt () in a string variable with the content you specify.

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

This actually returns an array:

 {"WORD1", "WORD2", "WORD3"} 
+1
source

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

String var = "WORD1_WORD2_WORD3";

The result of the string = var.Split ('_') [0];

0
source

Source: https://habr.com/ru/post/1285956/


All Articles