[英]Multiple occurrences of text in a string
如何使用for循環遍歷字符串中給定短語的每次迭代? 例如,說我有以下字符串:
嘿,這是一個示例字符串。 字符串是字符的集合。
而且,每當有一個“是”時,我想將其后的三個字符分配給一個新字符串。 我知道如何做到這一點,但我試圖弄清楚如何使用for循環遍歷同一單詞的多個實例。
這是你想要的嗎?
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個字符。 每場比賽分為兩組:
第一組:其中包括下一個威脅角色
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.