在 C# 中從給定字串中刪除所有重複項


下面是該字串。

string str = "ppqqrr";

現在,使用 Hashset 將字串對映到字元。這將從字串中刪除重複字元。

var res = new HashSet<char>(str);

讓我們來看完整的示例 −

示例

 線上演示

using System;
using System.Linq;
using System.Collections.Generic;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         string str = "ppqqrr";
         Console.WriteLine("Initial String: "+str);
         var res = new HashSet<char>(str);
         Console.Write("New String after removing duplicates:");
         foreach (char c in res){
            Console.Write(c);
         }  
      }
   }
}

輸出

Initial String: ppqqrr
New String after removing duplicates:pqr

更新於: 22-Jun-2020

361 瀏覽量

啟動您的 職業生涯

完成課程認證

開始
廣告