如何在特定点拆分字符串并收集拆分中间的内容?

How do I split a string at certain points and collect what's in the middle of the split?

假设我有一些示例文本

jordan went to the shop to buy some bread end

jordan sold some tomatos end

jordan went to see his father end

如果这是一个单独的字符串,我如何在单词 "Jordan" 和 "end" 处拆分此字符串以获取中间的文本并将其放入数组中?

我期望的输出是

string [] sArr = {
    "went to the shop to buy some bread",
    "sold some tomatos",
    "went to see his father"
}

尝试使用 Split() 方法:

String str = "jordan went to the...";
String[] separator = new String[] { "jordan", "end"};
String[] res = str.Split(separator, StringSplitOptions.RemoveEmptyEntries);

这将提供您正在寻找的输出。 请记住,它还会保留 end 和 jordan 之间的任何文本。

好吧,你可以使用正则表达式来完成:

var s = "jordan went to the shop to buy some bread end jordan sold some tomatos end jordan went to see his father end";
var list = new List<string>();
foreach (Match match in Regex.Matches(s, @"jordan (.*?) end"))
{
    if(match.Success)
        list.Add(match.Groups[1].Value);
}

var sArr = list.ToArray();

或者用 LINQ 可以做得更优雅:

var sArr = Regex.Matches(s, @"jordan (.*?) end")
    .Cast<Match>()
    .Where(m => m.Success)
    .Select(m => m.Groups[1].Value)
    .ToArray();

如果需要,您可以将它们替换为空字符串。试试这个:

string str1 = "jordan went to the shop to buy some bread end";
        string str2 = "jordan sold some tomatos end";
        string str3 = "jordan went to see his father end";
        string total = str1 + str2 + str3;
        if ((total.Contains("jordan")==true) ||(total.Contains("end")) )
        {
            total = total.Replace("jordan", "");
            total = total.Replace("end", "");
        }
        Console.WriteLine(total);