How to remove all characters from a string before a specific character

Suppose I have line A , for example:

 string A = "Hello_World"; 

I want to delete all characters before (and including) _ . The exact number of characters before _ may vary. In the above example, A == "World" after deletion.

+6
source share
6 answers
 string A = "Hello_World"; string str = A.Substring(A.IndexOf('_') + 1); 
+10
source
 string a = "Hello_World"; a = a.Substring(a.IndexOf("_")+1); 

try it? or = part in your A = Hello_World included?

+1
source

Try it:

  string input = "Hello_World" string output = input.Substring(input.IndexOf('_') + 1); output = World 

You can use the IndexOf method and the Substring method.

Create your function as follows

 public string RemoveCharactersBeforeUnderscore(string s) { string splitted=s.Split('_'); return splitted[splitted.Length-1] } 

Use this function as follows

 string output = RemoveCharactersBeforeUnderscore("Hello_World") output = World 
+1
source

You have already received a great answer . If you want to take another step, you can wrap a.SubString(a.IndexOf('_') + 1) in a reliable and flexible extension method:

 public static string TrimStartUpToAndIncluding(this string str, char ch) { if (str == null) throw new ArgumentNullException("str"); int pos = str.IndexOf(ch); if (pos >= 0) { return str.Substring(pos + 1); } else // the given character does not occur in the string { return str; // there is nothing to trim; alternatively, return `string.Empty` } } 

which you would use as follows:

 "Hello_World".TrimStartUpToAndIncluding('_') == "World" 
+1
source
 var foo = str.Substring(str.IndexOf('_') + 1); 
0
source
 string orgStr = "Hello_World"; string newStr = orgStr.Substring(orgStr.IndexOf('_') + 1); 
0
source

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


All Articles