3

你将如何从 C# 中的字符串中删除任何重复的子字符串?例如,在这个字符串中:

This is a test test string

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

This is a test string

或在

shift+shift+shift+shift+d

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

shift+d
4

1 回答 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));
        }
    }
}
于 2013-01-01T16:22:20.847 回答