如何从字符串中删除重复的子字符串?

时间:2012-12-30 20:20:23

标签: c# string

如何从c#中的字符串中删除任何重复的子字符串?例如,在此字符串中:

This is a test test string

将删除重复的“测试”,创建结果:

This is a test string

shift+shift+shift+shift+d

“shift + shift + shift +”将被移除,导致

shift+d

1 个答案:

答案 0 :(得分:0)

我希望你的问题本身可以通过不同的句子来删除重复的单词,并删除单词重复的字符。

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp
{
    internal class Program
    {
        private static void Main()
        {
            var input = new[] {"This is TEST TEST string", "shift+shift+shift+D"};
            foreach (string data in input)
            {
                bool contains = data.Contains((char)0x20);
                Console.WriteLine(contains ? StripFromSentence(data.TrimEnd(new[] {(char) 0x20})) : StripFromWord(data));
            }
            Console.ReadLine();
        }

        private static string StripFromWord(string word)
        {
            char[] chr = word.ToCharArray();
            var ap = new HashSet<char>();
            foreach (char s in chr)
                ap.Add(s);
            return ap.Aggregate(string.Empty, (current, c) => current + c);
        }

        private static string StripFromSentence(string sentence)
        {
            string[] strings = sentence.Split(new[] {(char) 0x20});
            var ap = new HashSet<string>();
            foreach (string s in strings)
                ap.Add(s);
            return ap.Aggregate(string.Empty, (current, word) => current + (word + (char)0x20));
        }
    }
}

我希望这可以解决你的问题。