【问题标题】:Get index of the first character of substring in a string in C# [duplicate]在C#中获取字符串中子字符串的第一个字符的索引[重复]
【发布时间】:2016-04-13 05:40:43
【问题描述】:

我想获取 xx in

的第一个字母的索引

xx INC FFFFFFFF xx DE RRRRRR

IndexOf 方法没有帮助。 有什么线索吗?

【问题讨论】:

标签: c# indexing substring


【解决方案1】:

您可以使用这样的扩展方法,它使用支持起始索引的overload of String.IndexOf。 StringComparison 可用于不区分大小写的比较:

public static IList<int> AllIndexOf(this string text, string str, StringComparison comparisonType = StringComparison.CurrentCulture)
{
    IList<int> allIndexes = new List<int>();
    int index = text.IndexOf(str, comparisonType);
    while (index != -1)
    {
        allIndexes.Add(index);
        index = text.IndexOf(str, index + str.Length, comparisonType);
    }
    return allIndexes;
}

那么就很简单了:

string str = "xx INC FFFFFFFF xx DE RRRRRR";
IEnumerable<int> allIndexes = str.AllIndexOf("xx", StringComparison.InvariantCulture); // 0 and 16

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多