I have a string which I would like to remove the first three characters from. How do I go about this using substrings, or is there any other way?
string temp = "01_Barnsley"
string textIWant = "Barnsley"
Thank you
I have a string which I would like to remove the first three characters from. How do I go about this using substrings, or is there any other way?
string temp = "01_Barnsley"
string textIWant = "Barnsley"
Thank you
You can use String.Substring(Int32)
method.
Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.
string textIWant = temp.Substring(3);
Here is a demonstration
.
As an alternative, you can use String.Remove method(Int32, Int32)
method also.
Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.
string textIWant = temp.Remove(0, 3);
Here is a demonstration
.
you can use String.Substring Method (Int32)
string textIWant = temp.Substring(3);
or String.Remove Method (Int32, Int32)
string textIWant = temp.Remove(0,3);
If there is a pattern to the data, one can use that to extract out what is needed using Regular Expressions.
So if one knows there are numbers (\d
regex for digits and with 1 or more with a +
) followed by an under bar; that is the pattern to exclude. Now we tell the parser what we want to capture by saying we want a group match using ( )
notation. Within that sub group we say capture everything by using .+
. The period (.
) means any character and the +
as seen before means 1 or more.
The full match for the whole pattern (not what we want) is grouped as at index zero. We want the first subgroup match at index 1 which is our data.
Console.WriteLine (Regex.Match("01_Barnsley", @"\d+_(.+)").Groups[1].Value); // Barnsley
Console.WriteLine (Regex.Match("9999_Omegaman", @"\d+_(.+)").Groups[1].Value); // Omegaman
Notice how we don't have to worry if its more than two digits? Whereas substring can fail because the number grew, it is not a problem for the regex parser due to the flexibility found in our pattern.
If there is a distinct pattern to the data, and the data may change, use regex. The minimal learning curve can pay off handsomely. If you truly just need something at a specific point that is unchanging, use substring.
A solution using LINQ:
string temp = "01_Barnsley";
string textIWant = new string(temp.Skip(3).ToArray());