Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring formatting to get all characters after the first underscore but before the 2nd underscore?

for example we have this string:

  • hello_my name_is_bob

and want to get only the "my Name" portion of the string, how could I get this simply with substring?

Also, the format in the example will always be the same so I just need to retrieve what is after the first underscore but before the 2nd underscore.

like image 505
MDL Avatar asked Dec 28 '11 18:12

MDL


1 Answers

string.Split will do for this, no need to go into Substring:

var parts = "hello_my name_is_bob".Split('_');

string name = parts[1] // == "my name";

Or, in a one liner (though I find this less readable):

string name = "hello_my name_is_bob".Split('_')[1];
like image 59
Oded Avatar answered Nov 15 '22 04:11

Oded