c# - .NET StringBuilder - 检查是否以字符串结尾

标签 c# .net string stringbuilder

检查 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/

相关文章:

c# - 在C#中使用参数委托(delegate)给其他线程

c# - 为什么可以通过类实例在 C# 中的静态方法中调用非静态方法

.net - 使用 Rijndael 算法为文件加密嵌入 IV 信息的正确位置在哪里?

c# - Databind 无法通过 IBindableComponent 进行转换

java - 使用扫描器 useDelimiter 解析文本

Java:尝试拆分 ", but string.split(""") 不被接受...这该怎么办?

c# - 在这种情况下,编译器真的强制我在密封类中使用 protected 吗?

c# - Excel/Quickbooks 数据到 c#

.net - 在不使用来自另一个线程的 Invoke/BeginInvoke 的情况下读取表单控件值(但不更改它)是否是线程安全的

java - 实现 Java 的 indexOf 方法(子串搜索)