Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best way to skip characters before underscore ( _ ) in a string using c#

Which is the best way to skip characters before underscore _ in a string using c#?

eg:case 1 String contain _

string s="abc_defg" 

I want to get defg to another string

case 2

some times string do not contain _ . at that time i need to get the all string

eg.

s="defg"

In both case i want get "defg" . Filtering only applied if there is an underscore in the string. How can i do that

like image 236
Null Pointer Avatar asked Dec 05 '22 19:12

Null Pointer


1 Answers

string s="abc_defg";
int ix = s.IndexOf('_');
s = ix != -1 ? s.Substring(ix + 1) : s;

using the ternary operator here is quite useless, better to write:

s = s.Substring(ix + 1);

directly, using the fact that Substring probably is optimized for the case index == 0

Is this what you want?

BUT someone has suggested using LINQ cannons, so

var temp = s.SkipWhile(p => p != '_').Skip(1);
s = temp.Any() ? new string(temp.ToArray()) : s;

In .NET 4.0 there is a new string.Concat method.

s = temp.Any() ? string.Concat(temp) : s;

(note that in general the LINQ way is slower and more complex to read)

I'll add the ultrakill: the Regular Expressions!!! There is a school of thought that anything can be done with Regular Expressions OR jQuery! :-)

var rx = new Regex("(?:[^_]*_)?(.*)", RegexOptions.Singleline);
var res = rx.Match(s).Groups[1].Value;

I won't even try to explain this beast to anyone, so don't ask. It's useless. (both the Regex and to ask :-) )

like image 101
xanatos Avatar answered Dec 29 '22 06:12

xanatos