【问题标题】:StringBuilder - find last index of a characterStringBuilder - 查找字符的最后一个索引
【发布时间】:2014-05-13 08:52:59
【问题描述】:

我想在StringBuilder 中查找特定的最后一个字符。
我知道,我可以使用 while() 解决它,但是有没有构建它的选项可以轻松做到这一点?

例如:

private static StringBuilder mySb = new StringBuilder("");
mySb.Add("This is a test[n] I like Orange juice[n] Can you give me some?");

现在:它应该找到] 并给我位置。喜欢:40

提前致谢

【问题讨论】:

  • 可能重复,你检查过这个stackoverflow.com/questions/12261344/… 吗?
  • 让我说清楚。是否需要获取] 的最后一个索引??请看看StringBuilder Extensions你会找到你需要的一切!!
  • 您可以在StringBuilder 上调用ToString,然后在string 上使用LastIndexOf...
  • fyi,索引将是 39,因为它的索引为 0。
  • 为什么不能检查字符串 before 将其附加到字符串生成器?

标签: c# .net


【解决方案1】:

由于没有内置方法,并且总是通过StringBuilder 通过ToString 创建一个string 效率很低,您可以为此创建一个扩展方法:

public static int LastIndexOf(this StringBuilder sb, char find, bool ignoreCase = false, int startIndex = -1, CultureInfo culture = null)
{
    if (sb == null) throw new ArgumentNullException(nameof(sb));
    if (startIndex == -1) startIndex = sb.Length - 1;
    if (startIndex < 0 || startIndex >= sb.Length) throw new ArgumentException("startIndex must be between 0 and sb.Lengh-1", nameof(sb));
    if (culture == null) culture = CultureInfo.InvariantCulture;

    int lastIndex = -1;
    if (ignoreCase) find = Char.ToUpper(find, culture);
    for (int i = startIndex; i >= 0; i--)
    {
        char c = ignoreCase ? Char.ToUpper(sb[i], culture) : (sb[i]);
        if (find == c)
        {
            lastIndex = i;
            break;
        }
    }
    return lastIndex;
}

将它添加到一个静态的、可访问的(扩展)类中,然后你可以这样使用它:

StringBuilder mySb = new StringBuilder("");
mySb.Append("This is a test[n] I like Orange juice[n] Can you give me some?");
int lastIndex = mySb.LastIndexOf(']');  // 39

【讨论】:

  • 始终使用当前区域性进行不区分大小写的比较可能不是一个好主意。土耳其语 iı 等。
  • @CodesInChaos:我已经编辑了我的答案,看看。我认为在比较字符时使用bool 作为参数就足够了,不是吗?
  • 我通常更喜欢传入 CultureInfo 或简单地在任何地方使用不变的文化,但是区域设置感知字符串函数在 .net 中是一团糟。不知道他们为什么默认使用当前本地。
【解决方案2】:

使用toString方法将StringBuilder转换为字符串,之后就可以使用LastIndexOf方法了。

mySb.ToString().LastIndexOf(']');

LastIndexOf:

报告最后一次出现的从零开始的索引位置 此实例中指定的 Unicode 字符或字符串。方法 如果在此实例中找不到字符或字符串,则返回 -1。

此成员已重载。有关此会员的完整信息, 包括语法、用法和示例,单击重载中的名称 列表。

【讨论】:

  • 是的,你可以。但是,如果您在循环中执行此操作,您将始终从完整的StringBuilder 创建一个新字符串,只是为了找到一个索引。这可能是非常低效的。我建议创建在 StringBuilder 本身上使用循环的方法/扩展。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 2011-03-24
  • 1970-01-01
  • 2013-09-18
  • 2010-11-06
  • 2013-05-06
相关资源
最近更新 更多