What is the best way to skip characters before underscore (_) in string using C #

What is the best way to skip characters before underscoring _ in a string using C #?

for example: case 1 The string contains _

 string s="abc_defg" 

I want to get defg for another line

case 2

multiple lines of a line do not contain _ . at that time I need to get the whole line

eg.

 s="defg" 

In both cases, I want to get "defg". Filtering is applied only if there is an underscore in the string. How can i do this

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

using the ternary operator is completely useless here, it’s better to write:

 s = s.Substring(ix + 1); 

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

Is this what you want?

BUT someone suggested using LINQ guns, so

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

.NET 4.0 introduces a new string.Concat method.

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

(note that in general, the LINQ method is slower and harder to read)

I will add ultrakill: Regular expressions !!! There is a school of thought that everything can be done using regular expressions OR jQuery! :-)

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

I will not even try to explain this beast to anyone, so do not ask. It's useless. (both regex and ask :-))

+6
source

I don’t know how to determine the best way, but it works as long as there is only one underline.

 string s1 = "abc_defg"; string s2 = "defg"; Console.WriteLine( s1.Split('_').Last() ); Console.WriteLine( s2.Split('_').Last() ); 

If you need more flexibility, you can take a look at regular expressions.

 Regex.Replace(s1, "^.*_", "") 
+6
source

You can use LINQ SkipWhile () :

 textValue.SkipWhile(c => c != separator) .Skip(1) 

The final solution for both cases:

 string textValue = "abc_defg"; char separator = '_'; string result = textValue.IndexOf(separator) >= 0 ? new String(textValue.SkipWhile(c => c != separator) .Skip(1) .ToArray()) : textValue; 

EDIT:

I am right with the xanatos comment, but in any case it is sometimes very interesting to find various solutions :)

+2
source

simple function, perhaps:

 public string TakeStringAfterUnderscoreOrWholeString(string input) { var underscorePos = input.IndexOf("_"); return underscorePos == -1 ? input : input.Substring(underscorePos+1); } 

Live test: http://rextester.com/rundotnet?code=AVQO61388

+2
source

I would suggest just using the string [] arr and the split function for this purpose.

 string[] arr=s.split('_'); string out=arr[arr.Length-1]; 
0
source

All Articles