如何查找字符串中某个特定句子的所有出现? [英] How do I find all occurrences of a specific sentence within a string?
本文介绍了如何查找字符串中某个特定句子的所有出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个像这样的字符串:
Let's say I had a string like this:
string source = "Today is friday! I'm am having trouble programming this. Today is friday! Tomorrow is saturday. Today is friday!"
我想搜索这个字符串,抓住所有说今天是星期五!"的句子,然后用刚刚找到的句子创建一个新的字符串.
I want to search through this string, grab all the sentences that say "Today is friday!", and create a new string with the sentences I just found.
上述字符串的预期结果是:
The expected result from the above string is:
string output = "Today is friday!Today is friday!Today is friday!"
LINQ不是必需的.
谢谢!
推荐答案
这是一种非LINQ的方法:
Here's a non-LINQ method of doing it:
string str = "Today is friday! I'm am having trouble programming this. Today is friday! Tomorrow is saturday. Today is friday!";
StringBuilder sb = new StringBuilder();
int index = 0;
do
{
index = str.IndexOf("Today is friday!", index);
if (index != -1)
{
sb.Append("Today is friday!");
index++;
}
} while (index != -1);
string repeats = sb.ToString();
这篇关于如何查找字符串中某个特定句子的所有出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文