C# 程式可從指定語句中去除所有重複出現的單詞
設定一個包含重複單詞的字串。
string str = "One Two Three One";
上面您可以看到單詞“One”出現了兩次。
如要移除重複單詞,您可以在 C# 中嘗試執行以下程式碼 −
示例
using System; using System.Linq; public class Program { public static void Main() { string str = "One Two Three One"; string[] arr = str.Split(' '); Console.WriteLine(str); var a = from k in arr orderby k select k; Console.WriteLine("After removing duplicate words..."); foreach(string res in a.Distinct()) { Console.Write(" " + res.ToLower()); } Console.ReadLine(); } }
輸出
One Two Three One After removing duplicate words... one three two
廣告