如何从字符串中删除重复的子字符串? [关闭]

问题描述 投票:3回答:1

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

This is a test test string

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

This is a test string

或在

shift+shift+shift+shift+d

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

shift+d
c# string
1个回答
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));
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.