Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 942
Waqar Ahmed Avatar asked Nov 28 '14 06:11

Waqar Ahmed


People also ask

How do I remove all characters from a string after a specific character?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .

How do I remove all characters before a character in Java?

s1. trim() . trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.)


3 Answers

string A = "Hello_World";
string str = A.Substring(A.IndexOf('_') + 1);
like image 181
Arshad Avatar answered Sep 19 '22 13:09

Arshad


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"
like image 27
stakx - no longer contributing Avatar answered Sep 19 '22 13:09

stakx - no longer contributing


string a = "Hello_World";
a = a.Substring(a.IndexOf("_")+1);

try this? or is the A= part in your A=Hello_World included?

like image 31
Vajura Avatar answered Sep 17 '22 13:09

Vajura