簡體   English   中英

字符串中多次出現文本

[英]Multiple occurrences of text in a string

如何使用for循環遍歷字符串中給定短語的每次迭代? 例如,說我有以下字符串:

嘿,這是一個示例字符串。 字符串是字符的集合。

而且,每當有一個“是”時,我想將其后的三個字符分配給一個新字符串。 我知道如何做到這一點,但我試圖弄清楚如何使用for循環遍歷同一單詞的多個實例。

如果出於某種原因必須使用for循環,則可以將ja72 提供代碼的相關部分替換為:

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

不幸的是,我沒有足夠的聲譽在此處添加此評論,因此將其發布為答案!

這是你想要的嗎?

    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 "

您可以使用以下正則表達式:

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

此正則表達式查找is (?:is) ,並接受接下來的三個字符(.{3})

然后,使用正則表達式查找所有匹配項: Regex.Matches() 這將返回一個符合每個is字符串中,其次是3個字符。 每場比賽分為兩組:

  • 組0:包括is和接下來的三個字符
  • 第一組:其中包括下一個威脅角色

    Matches matchs = re.Matches(“嘿,這是示例字符串。字符串是字符的集合。”); StringBuilder sb = new StringBuilder(); foreach(匹配中匹配m個){sb.Append(m.Groups 1 .Value); }

使用Regex比遍歷字符串中的字符要快得多。 如果在Regex構造函數中使用RegexOptions.Compiled ,則更多: Regex構造函數(字符串,RegexOptions)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM