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
廣告