How to remove non-duplicate characters from string in C#

1 Answer

0 votes
using System;
using System.Text;
using System.Collections.Generic;

public class Program
{
	 public static string removeNonDuplicate(string str) {
		char[] arr = str.ToCharArray();

		IList<char> duplicateList = new List<char>();

		foreach (char ch in arr) {
			if (str.IndexOf(ch) != str.LastIndexOf(ch)) {
				duplicateList.Add(ch);
			}
		}

		StringBuilder duplicateString = new StringBuilder();
		foreach (char ch in duplicateList) {
			duplicateString.Append(ch);
		}

		return duplicateString.ToString();
	 }

	public static void Main(string[] args)
	{
		string str = "Bubble Occurrence Mammal c#";

		Console.WriteLine(removeNonDuplicate(str));
	}
}



/*
run:

ubble ccurrece ammal aa

*/

 



answered Mar 20, 2024 by avibootz

Related questions

1 answer 223 views
1 answer 204 views
2 answers 311 views
1 answer 227 views
1 answer 198 views
1 answer 224 views
1 answer 187 views
...