Reputation: 325
How can I substring a character until the end of the text which the length of the string always changes? I need to get everything after the ABC The samples are:
ABC123
ABC13245
ABC123456
ABC1
Upvotes: 6
Views: 27709
Reputation: 141752
var startIndex = "ABC".Length;
var a = "ABC123".Substring(startIndex); // 123
var b = "ABC13245".Substring(startIndex); // 13245
var c = "ABC123456".Substring(startIndex); // 123456
car d = "ABC1".Substring(startIndex); // 1
Substring()
- Fasterstring.Substring(int startIndex) returns all the characters after startIndex
. Here it is as a method you can use.
public static string SubstringAfter(string s, string after)
{
return s.Substring(after.Length);
}
Remove()
- Slightly Slowerstring.Remove(int start, int count) returns a new string after removing count
characters beginning with the character at index start
.
public static string SubstringAfter(string s, string after)
{
return s.Remove(0, after.Length);
}
Substring()
and IndexOf()
- Slower StillIf your string started with something other than ABC
, and if you wanted to get everything after ABC
, then, as Greg rightly answered, you would use IndexOf()
.
var s = "123ABC456";
var result = s.Substring(s.IndexOf("ABC") + "ABC".Length)); // 456
Here's a demo, which also shows which is fastest.
using System;
public class Program
{
public static void Main()
{
var result = "ABC123".Substring("ABC".Length);
Console.WriteLine(result);
Console.WriteLine("---");
Test(SubstringAfter_Remove);
Test(SubstringAfter_Substring);
Test(SubstringAfter_SubstringWithIndexOf);
}
public static void Test(Func<string, string, string> f)
{
var array =
new string[] { "ABC123", "ABC13245", "ABC123456", "ABC1" };
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
foreach(var s in array) {
Console.WriteLine(f.Invoke(s, "ABC"));
}
sw.Stop();
Console.WriteLine(f.Method.Name + " : " + sw.ElapsedTicks + " ticks.");
Console.WriteLine("---");
}
public static string SubstringAfter_Remove(string s, string after)
{
return s.Remove(0, after.Length);
}
public static string SubstringAfter_Substring(string s, string after)
{
return s.Substring(after.Length);
}
public static string SubstringAfter_SubstringWithIndexOf(string s, string after)
{
return s.Substring(s.IndexOf(after) + after.Length);
}
}
Output
123
---
123
13245
123456
1
SubstringAfter_Remove : 2616 ticks.
---
123
13245
123456
1
SubstringAfter_Substring : 2210 ticks.
---
123
13245
123456
1
SubstringAfter_SubstringWithIndexOf : 2748 ticks.
---
Upvotes: 11
Reputation: 15381
string search = "ABC";
string result = input.Substring(input.IndexOf(search) + search.Length);
Upvotes: 18