Waqar Ahmed
Waqar Ahmed

Reputation: 203

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.

Upvotes: 10

Views: 24409

Answers (6)

Zia
Zia

Reputation: 755

you can do this by creating a substring.

simple exampe is here:

public static String removeTillWord(String input, String word) {
    return input.substring(input.indexOf(word));
}

removeTillWord("I need this words removed taken please", "taken");

Upvotes: -1

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"

Upvotes: 2

Rohit
Rohit

Reputation: 1550

string orgStr = "Hello_World";
string newStr = orgStr.Substring(orgStr.IndexOf('_') + 1);

Upvotes: 0

Mohammad Arshad Alam
Mohammad Arshad Alam

Reputation: 9862

string A = "Hello_World";
string str = A.Substring(A.IndexOf('_') + 1);

Upvotes: 16

Vajura
Vajura

Reputation: 1132

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

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

Upvotes: 1

Jerry Bian
Jerry Bian

Reputation: 4228

var foo = str.Substring(str.IndexOf('_') + 1);

Upvotes: 0

Related Questions