gpt4 book ai didi

c# - StringBuilder - 查找字符的最后一个索引

转载 作者:行者123 更新时间:2023-11-30 22:06:31 25 4
gpt4 key购买 nike

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

例如:

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

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

提前致谢

最佳答案

由于没有内置方法并且总是通过 ToStringStringBuilder 创建一个 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

关于c# - StringBuilder - 查找字符的最后一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23626703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com