CSharpNewBee
CSharpNewBee

Reputation: 1981

trying to remove unique words from a string

My code believe needs to remove unique instancs of the same word (Complete word).

What do I mean by complete words. Well, given the following string:

THIIS IS IS A TEST STRRING

I need this returned:

THIIS IS A TEST STRRING

My code returns this:

THIS IS A TEST STRING

            var items = sString.Split(' ');
            var uniqueItems = new HashSet<string>(items);
            foreach (var item in uniqueItems)
            {
                strBuilder.Append(item);
                strBuilder.Append(" ");
            }

           finalString =  strBuilder.ToString().TrimEnd();

How can i therefore, retain an instance of a duplicate characters within a word, but remove complete duplicate words entirley?

Upvotes: 0

Views: 116

Answers (2)

Zain Ul Abidin
Zain Ul Abidin

Reputation: 2700

bro Call this method i know its a bit complex and lengthy but you will be amazed after getting the results!

public string IdentifySamewords(string str)
{
   string[] subs=null;
   char[] ch=str.ToCharArray();
   int count=0;
   for(int i=0;i<ch.Length;i++)
   {
     if(ch[i]==' ')
       count++;
   }
   count++;
   subs=new string[count];
   count=0;
   for(int i=0;i<ch.Length;i++)
   {
      if(ch[i]==' ')
       count++;
      else
       subs[count]+=ch[i].ToString();
   }
   string current=null,prev=null,res=null;
   for(int i=0;i<subs.Length;i++)
   {
      current=subs[i];
      if(current!=prev)
        res+=current+" ";

      prev=current;
   }
  return res;
}

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You need Split and Distinct

var words = "THIIS IS IS A TEST STRRING".Split(' ').Distinct();

var result = string.Join(" ", words);

Upvotes: 3

Related Questions