using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excercises
{
public class PhoneBook
{
Dictionary
StringBuilder builder = new StringBuilder();
public void removeDups(string input)
{
//Split the string into words separated by a space (' ')
string[] myStr = input.Split(' ');
//traverse the array
for (int i =0;i (less than) myStr.Length; i++)
{
//if the word already exists as a key in the dictionary, just add the count other wise add the count as 1 and the key
if (Unique.ContainsKey(myStr[i]))
{
Unique[myStr[i]]++;
}
else
{
Unique.Add(myStr[i], 1);
}
}
//for every key in the dictionary, add that to the stringbuilder if the word is uniqie. If the word is not unique add only 1 key
foreach (var d in Unique)
{
if (d.Value == 1)
{
builder.Append(d.Key);
builder.Append(' ');
}
else
{
builder.Append(' ');
builder.Append(d.Key);
builder.Append(' ');
}
}
Console.WriteLine(builder.ToString());
}
}
class Program
{
static void Main(string[] args)
{
PhoneBook Book = new PhoneBook();
string str = "This is a test sentence for my test purposes only. I am a test resource";
Book.removeDups(str);
Console.ReadKey();
}
}
}
1 comment:
Another implementation of the same problem. This time splitting with punctuations and in the return don't include spaces.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practice
{
class Program
{
static void Main(string[] args)
{
string input = "Reversing a singly linked list is about very easy. The SLinkList Reverse(SLinkList head) function is about ten lines of code that does the magic singly.";
char[] delimiters = {' ','.', '(', ')' };
string[] words = (input.ToLower()).Split(delimiters);
//foreach (var v in words)
// Console.WriteLine(v);
//Console.ReadKey();
Dictionary Dic = new Dictionary();
foreach (var v in words)
{
if (Dic.ContainsKey(v))
{
Dic[v]++;
}
else
{
Dic.Add(v, 1);
}
}
foreach (var d in Dic)
{
if (d.Value == 1 && d.Key!="")
{
Console.WriteLine(d.Key);
}
else if (d.Value > 1 && d.Key!="")
{
Console.WriteLine(d.Key);
}
}
Console.ReadKey();
}
}
}
Post a Comment