c# - Reversal and removing of duplicates in a sentence -


i preparing interview question.one of question revert sentence. such "its awesome day" "day awesome its. after this,they asked if there duplication, can remove duplication such "i good, good" "good is, i".

for reversal of sentence have written following method

public static string reversesentence(string one) {     stringbuilder builder = new stringbuilder();      string[] split = one.split(' ');     (int = split.length-1; >= 0; i--)     {          builder.append(split[i]);         builder.append(" ");     }     return builder.tostring();  } 

but not getting ideas on removing of duplication.can here.

this works:

public static string reversesentence(string one) {     regex reg = new regex("\\w+");     bool isfirst = true;     var usedwords = new hashset<string>(stringcomparer.invariantcultureignorecase);     return string.join("", one.split(' ').reverse().select((w => {         var trimmedword = reg.match(w).value;         if (trimmedword != null) {             var wasfirst = isfirst;             isfirst = false;              if (usedwords.contains(trimmedword)) //is duplicate?                 return w.replace(trimmedword, ""); //remove duplicate phrase keep punctuation              usedwords.add(trimmedword);              if (!wasfirst) //if it's first word, don't add leading space                 return " " + w;             return w;         }         return null;     }))); } 

basically, decide if it's distinct based on word without punctuation. if exists, return punctuation. if doesn't exist, print out whole word including punctuation.

punctuation removes space in example, why can't string.join(" ", ...) (otherwise result good , i instead of good is, i

test:

reversesentence("i good, good").dump();

result:

good is, i


Comments