【问题标题】:Multiple occurrences of text in a string字符串中多次出现文本
【发布时间】:2012-05-23 00:31:22
【问题描述】:

如何使用 for 循环遍历字符串中给定短语的每次迭代?例如,假设我有以下字符串:

嘿,这是一个示例字符串。字符串是字符的集合。

每次出现“is”时,我都想将它后面的三个字符分配给一个新字符串。我知道如何做到这一点,但我试图弄清楚如何使用 for 循环来遍历同一个单词的多个实例。

【问题讨论】:

  • 你想要类似的东西吗: string st = "嘿,这是一个示例字符串。字符串是字符的集合。"; st=st.replace("is","is+3char"); var arrayOfSplittedSts = st.Split(new[]{"is+3char"}, System.StringSplitOptions.None); ?

标签: c# string loops for-loop find


【解决方案1】:

如果您出于某种原因必须使用 for 循环,则可以将 code provided 的相关部分替换为 ja72:

for (int i = 0; i < text.Length; i++)
{
    if (text[i] == 'i' && text[i+1] == 's')
        sb.Append(text.Substring(i + 2, 3));
}

不幸的是,我没有足够的声誉在此处将此作为评论添加,因此将其发布为答案!

【讨论】:

    【解决方案2】:

    这是你想要的吗?

        static void Main(string[] args)
        {
            string text=@"Hey, this is an example string. A string is a collection of characters.";
    
            StringBuilder sb=new StringBuilder();
            int i=-1;
            while ((i=text.IndexOf("is", i+1))>=0)
            {
                sb.Append(text.Substring(i+2, 3));
            }
            string result=sb.ToString();
        }
    
    
    //result " is an a "
    

    【讨论】:

      【解决方案3】:

      您可以像这样使用正则表达式:

        Regex re = new Regex("(?:is)(.{3})");
      

      这个正则表达式查找的是(?:is),并取接下来的三个字符(.{3})

      然后您使用正则表达式查找所有匹配项:Regex.Matches()。这将为在字符串中找到的每个 is 返回一个匹配项,后跟 3 个字符。每场比赛有两组:

      • 第 0 组:包括 is 和接下来的三个字符
      • 第 1 组:包括下一个字符

        Matches matches = re.Matches("嘿,这是一个示例字符串。字符串是字符的集合。"); StringBuilder sb = new StringBuilder(); foreach(匹配 m 匹配) { sb.Append(m.Groups1.Value); }

      使用正则表达式比遍历字符串的字符要快得多。如果您在正则表达式构造函数中使用RegexOptions.Compiled,则更多:Regex Constructor (String, RegexOptions)

      【讨论】:

        猜你喜欢
        • 2016-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-08
        • 1970-01-01
        • 2017-04-16
        • 2011-04-21
        相关资源
        最近更新 更多