如何将字符子字符串子串直到文本末尾,字符串的长度总是在变化?我需要在ABC之后获得所有内容样本是:
ABC123
ABC13245
ABC123456
ABC1
Run Code Online (Sandbox Code Playgroud)
Gre*_*nis 12
string search = "ABC";
string result = input.Substring(input.IndexOf(search) + search.Length);
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Substring()-更快string.Substring(int startIndex)返回之后的所有字符startIndex。这是您可以使用的一种方法。
public static string SubstringAfter(string s, string after)
{
return s.Substring(after.Length);
}
Run Code Online (Sandbox Code Playgroud)
Remove()-稍慢string.Remove(int start,int count)删除count以index处的字符开头的字符后,返回一个新字符串start。
public static string SubstringAfter(string s, string after)
{
return s.Remove(0, after.Length);
}
Run Code Online (Sandbox Code Playgroud)
Substring()和IndexOf()-更慢如果您的字符串以以外的其他字符开头ABC,并且您想在之后获取所有内容ABC,那么按照Greg正确回答的说明,您可以使用IndexOf()。
var s = "123ABC456";
var result = s.Substring(s.IndexOf("ABC") + "ABC".Length)); // 456
Run Code Online (Sandbox Code Playgroud)
这是一个演示,还显示了最快的演示。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出量
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.
---
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8586 次 |
| 最近记录: |