0

在 if 语句的这个多值异常中,如果给定字符串中存在列表中的任何值,则我接受条件,然后从字符串中删除此值:

using System;
using System.Collections.Generic;
using System.Linq;

namespace _01_WORKDOC
{
    class Program
    {
        static void Main(string[] args)
        {
            string searchin = "You cannot successfully determine beforehand which side of the bread to butter"; 
            var valueList3 = new List<string> { "successfully", "determine", "bread", "the", "to" }; 

            if (valueList3.Any(searchin.Contains)) 
            {
                string exceptions3 = "successfully determine bread the to"; 
                string[] exceptionsList3 = exceptions3.Split(' ');
                string test3 = searchin;
                string[] wordList3 = test3.Split(' ');
                string outtxt = null;
                var text = wordList3.Except(exceptionsList3).ToArray();
                outtxt = String.Join(" ", text);

                Console.WriteLine("Input: " + searchin + "\nOutput: " + outtxt + "\n");              
            }
            Console.Read();
        }
    }
}

我的问题是如何在这段代码中保留异常并删除除此词之外的所有其他内容。所以实际结果是:

Input: "You cannot successfully determine beforehand which side of the bread to butter"
Output: "You cannot beforehand which side of butter"

var valueList3 = new List<string> { "successfully", "determine", "the", "bread", "to" };但是,如果使用同一个列表我想得到这个结果,我该怎么办。

Input: "You cannot successfully determine beforehand which side of the bread to butter"
Output: "successfully determine the bread to"

正确地说我想要两个相同的声明:

 Input: "You cannot successfully determine beforehand which side of the bread to butter"
 Output A: "You cannot beforehand which side of butter"
 Output B: "successfully determine the bread to"

当然,我不是在要求这个:

var valueList3 = new List<string> { "You", "cannot", "beforehand", "which", "side", "of", "butter" }; 

但列表相同:

  var valueList3 = new List<string> { "successfully", "determine", "the", "bread", "to" };
4

1 回答 1

0

所以这段代码:

string text = "You cannot successfully determine beforehand which side of the bread to butter"; 
var words = new List<string>{ "successfully", "determine", "the", "bread", "to" };

var foundWords = string.Join(" ", words.Where(word => text.Contains(word)));

Console.WriteLine("Input: " + text + "\nOutput: " + foundWords + "\n"); 

将给出这个输出:

  • 输入:你无法事先成功确定要涂黄油的面包的哪一面
  • 输出:成功确定面包到
于 2016-09-09T00:46:34.510 回答