我想在中找到特定的最后一个字符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?");
Run Code Online (Sandbox Code Playgroud)
现在:应该找到]并给我所有权。喜欢:40
提前致谢
由于没有内置方法,因此始终string无法StringBuilder通过过孔创建通孔,ToString因此您可以为此创建扩展方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
将其添加到静态的,可访问的(扩展)类中,然后可以通过以下方式使用它:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2901 次 |
| 最近记录: |