Question

What is the best way to remove a few characters from the beginning of a string?

sName = "IMG: Testing again"  
sName = "TXT: This is amazing"

So remove IMG: and TXT.. etc...

So I can have this?

sName = "Testing again"   
sName = "This is amazing"
Was it helpful?

Solution

Well if its always gonna be four characters you could do. sName = sName.Substring(5)

OTHER TIPS

I personally like a simple regular expression for tasks like this.

var result = Regex.Replace(input, @"^[A-Z]+:\s*", "");

This has slightly different semantics than the other methods presented in what it will remove, so here the match is explained (also refer to the regular expression quick reference).

^         # anchor match to start of input
[A-Z]+    # match one or more capital English-alphabet characters
:         # match a colon
\s*       # match zero or more spaces

As such this approach also match input like "HELLOWORLDILOVEYOU:said Fred" and get rid of extra leading spaces in "TXT:    Wut?".

Assuming you always use the format {TYPE}: {Text}, and you want the {Text}, use this:

int index = sName.IndexOf(':') + 2; // two:  one for the colon and one for the space
sName = sName.Substring(index);

This can, of course, be put into one line; I have it broken into two for clarity.

You can also make an extension method for the general case:

public static string SubstringAfter(this string str, string sequence)
{
    int index = str.IndexOf(sequence);
    if (index > -1)
    {
        return str.Substring(str.IndexOf(sequence) + sequence.Length);
    }
    return str;
}

This lets you do this:

sName = sName.SubstringAfter(": ");

I would suggest you to go for a split if its a fixed format. See the code. After splitting the 1st index will have your item.

var sName = sName.Split( new char[] {':'})[1].Trim();
 sName = sName.Remove(0,5); //simple but not perfect way

Edited:

 sName= sName.Split(':')[1]; //For splitting by ':'
 sName = sName.Remove(0,1); //For the space, or use sName.Trim();

You could use

sName = sName.SubString(4, sname.Length)

It will a substring from the 4th position to the last position of the string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top