通过字符串的所有部分获取带有输入的子字符串

时间:2018-08-13 02:27:13

标签: c# regex string linq substring

我正在尝试从字符串中获取子字符串:

        List<string> list = new List<string>() { "boat in sea" };

        string input1 = "boat";
        string input2 = "sea";

        foreach (var x in list)
        {
            string res1 = x.Substring(x.IndexOf(input1) + input1.Length);   

            string res2 = x.Substring(x.IndexOf(input2) + input2.Length);

            Console.WriteLine("Res 1: " + res1 + "\nRes 2: " + res2);
        }

我当前的输出:

Res 1: in sea
Res 2:

但是我想要的输出:

Res 1: in sea
Res 2: boat in

但列表"sea in boat"中没有List<string> list = new List<string>() { "boat in sea", "sea in boat" };,但只有上述的"boat in sea"List<string> list = new List<string>() { "boat in sea" };

3 个答案:

答案 0 :(得分:0)

将第2行更改为

string res2 = x.Substring(0, x.IndexOf(input2) - 1);

此外,如果找不到字符串,则应该处理IndexOf返回-1的情况。

答案 1 :(得分:0)

我将通过以下方式寻求解决方案:

string text = "boat in sea";

string [] textSplitted = text.Split(“” .ToCharArray(),StringSplitOptions.RemoveEmpty ...);

现在textSplitted Array就像: [0] =“船”,[1] =“在”,[2] =“海”

知道了2个输入(必须在其间找到子字符串)之后-简单的搜索和带有空格的连接。

例如:Input1 =船&Input2 =海上

遍历数组并匹配船。如果找到,则继续连接数组中的所有字符串(中间有空格),直到找到Input2。 在此示例中-您只会获得“参与”

现在两个结果将是Input1 +“” +“ in”&“ in” +“” + Input2

答案 2 :(得分:0)

Linq 事物将删除单词列表中单词的首次出现。
作为一种选择,它将删除所述列表中所有出现的单词。

CheckList数组包含要删除的单词:

string[] Words = new[] { "boat in sea", "cat on roof", "big bat on boat", "sea side boat ride" };
string[] CheckList = new[] { "boat", "sea", "cat" };

var result = Words.SelectMany(s => new[] {
    CheckList.Where(sub => s.Contains(sub))
             .Select(sub => s.Remove(s.IndexOf(sub), sub.Length).Trim()
    });

要删除所有出现的内容,请用以下内容替换之前的Select()

.Select(sub => s.Replace(sub, string.Empty))

打印结果(两种方法都打印相同的列表,并带有当前选择的单词):

foreach (var StrippedLines in result)
{
    foreach (var s in StrippedLines)
        Console.WriteLine(s);
    Console.WriteLine("--------------");
}

in sea
boat in
--------------
on roof
--------------
big bat on
--------------
sea side ride
side boat ride
--------------
相关问题