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 130 views
1 answer 120 views
2 answers 183 views
1 answer 142 views
1 answer 123 views
1 answer 123 views
1 answer 103 views
...