簡體   English   中英

如何刪除if語句具有多個值的字符串中的所有異常(例外)

[英]How to remove all except exception in string with multiple value for if-statement

在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" };

所以這段代碼:

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"); 

將給出此輸出:

  • 輸入:您無法預先成功確定要在面包的哪一側塗黃油
  • 輸出:成功確定面包

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM