How to remove all characters from a string before a specific character
20,247
Solution 1
string A = "Hello_World";
string str = A.Substring(A.IndexOf('_') + 1);
Solution 2
You have already received a perfectly fine answer. If you are willing to go one step further, you could wrap up the a.SubString(a.IndexOf('_') + 1)
in a robust 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 like this:
"Hello_World".TrimStartUpToAndIncluding('_') == "World"
Solution 3
string a = "Hello_World";
a = a.Substring(a.IndexOf("_")+1);
try this? or is the A= part in your A=Hello_World included?
![Waqar Ahmed](https://i.stack.imgur.com/HTEux.jpg?s=256&g=1)
Author by
Waqar Ahmed
Updated on July 23, 2020Comments
-
Waqar Ahmed almost 4 years
Suppose I have a string
A
, for example:string A = "Hello_World";
I want to remove all characters up to (and including) the
_
. The exact number of characters before the_
may vary. In the above example,A == "World"
after removal.