检查 StringBuilder
是否最好(最短和最快)的方法是什么?以特定字符串结尾?
如果我只想检查一个字符,那不是问题sb[sb.Length-1] == 'c'
, 但如何检查它是否以更长的字符串结尾?
我可以考虑从 "some string".Length
开始循环并一个一个地阅读字符,但也许存在更简单的东西? :)
最后我想要这样的扩展方法:
StringBuilder sb = new StringBuilder("Hello world");
bool hasString = sb.EndsWith("world");
最佳答案
为避免生成完整字符串的性能开销,您可以使用 ToString(int,int)
采用索引范围的重载。
public static bool EndsWith(this StringBuilder sb, string test)
{
if (sb.Length < test.Length)
return false;
string end = sb.ToString(sb.Length - test.Length, test.Length);
return end.Equals(test);
}
编辑:可能需要定义一个带有StringComparison
参数的重载:
public static bool EndsWith(this StringBuilder sb, string test)
{
return EndsWith(sb, test, StringComparison.CurrentCulture);
}
public static bool EndsWith(this StringBuilder sb, string test,
StringComparison comparison)
{
if (sb.Length < test.Length)
return false;
string end = sb.ToString(sb.Length - test.Length, test.Length);
return end.Equals(test, comparison);
}
Edit2:正如 Tim S 在评论中指出的那样,我的回答(以及所有其他假设基于字符的平等的答案)存在缺陷影响某些 Unicode 比较。 Unicode 不要求两个(子)字符串具有相同的字符序列才能被视为相等。例如,预组合字符 é
应被视为等于字符 e
后跟组合标记 U+0301
。
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
string s = "We met at the cafe\u0301";
Console.WriteLine(s.EndsWith("café")); // True
StringBuilder sb = new StringBuilder(s);
Console.WriteLine(sb.EndsWith("café")); // False
如果您想正确处理这些情况,最简单的方法可能是调用 StringBuilder.ToString()
,然后使用内置的 String.EndsWith
。
关于c# - .NET StringBuilder - 检查是否以字符串结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17580150/