使用
带
如何对字符进行子字符串,直到字符串长度始终更改的文本末尾?我需要在 ABC 之后得到一切这些示例是:
ABC123
ABC13245
ABC123456
ABC1
string search = "ABC";
string result = input.Substring(input.IndexOf(search) + search.Length);
答案
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()
- 更快
字符串。子字符串(int startIndex) 返回 startIndex
之后的所有字符。这是您可以使用的方法。
public static string SubstringAfter(string s, string after)
{
return s.Substring(after.Length);
}
带Remove()
- 稍慢
字符串。Remove(int start, int count) 在删除索引 start
处的字符开头的count
字符后返回一个新字符串。
public static string SubstringAfter(string s, string after)
{
return s.Remove(0, after.Length);
}
Substring()
和IndexOf()
- 更慢
如果你的字符串以 ABC
以外的内容开头,并且如果你想在 ABC
之后得到所有内容,那么,正如 Greg 正确回答的那样,你会使用 IndexOf()
。
var s = "123ABC456";
var result = s.Substring(s.IndexOf("ABC") + "ABC".Length)); // 456
证明
这是一个演示,其中还显示了最快的。
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);
}
}
输出
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.
---