【问题标题】:How can I return the index of the second word in a string that can have multiple white spaces followed by one word followed by multiple white spaces? [closed]如何返回字符串中第二个单词的索引,该字符串可以有多个空格,后跟一个单词,后跟多个空格? [关闭]
【发布时间】:2015-01-01 05:26:19
【问题描述】:
String str ="  vol   ABCD C  XYZ";

我想返回“A”的索引

注意:包括第一个单词在内的所有单词之前都有多个空格。

【问题讨论】:

    标签: c# string parsing substring


    【解决方案1】:

    这将获得原始示例中 A 的索引 (String str =" vol ABCD C XYZ";):

    int indexOfABCD = str.IndexOf(str.Trim()[str.Trim().IndexOf(' ')+1]);
    

    如果您有类似String str = " vol ABCD C XYZ"; 的内容,其中有多个空格:

            string secondword = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)[1];
            int indexOfAinABCD = str.IndexOf(secondword.First());
    

    如果要获取第二个单词中所有字母的索引:

            IEnumerable<int> fullindex =  Enumerable.Range(indexOfAinABCD, secondword.Length);
    

    编辑:

    如果您在第一个单词中的其他任何地方都有 A,这将失败。您应该通过正则表达式获得完全匹配:

    int indexOfAinABCD = Regex.Match(str, string.Format(@"\W{0}\W",secondword)).Index+1;
    IEnumerable<int> fullindex =  Enumerable.Range(indexOfAinABCD, secondword.Length);
    

    所以像String str = " vABCDol ABCD C XYZ"; 这样的东西不会成为问题

    【讨论】:

    • 请注意,如果第二个单词的第一个字母也出现在第一个单词的某处,这将失败。
    • 谢谢!修正了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    相关资源
    最近更新 更多