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

3
你如何在C#中去除字符串中的重复子串?例如,在这个字符串中:
This is a test test string

重复的 "test" 将被移除,从而产生以下结果:
This is a test string

或者在
shift+shift+shift+shift+d

"shift+shift+shift+" 将被移除,结果为:
shift+d

18
听起来危险:http://en.wikipedia.org/wiki/Buffalo_buffalo_Buffalo_buffalo_buffalo_buffalo_Buffalo_buffalo - Hans Passant
1
https://dev59.com/VWDVa4cB1Zd3GeqPg84Y - Robert Harvey
8
“这是一个测试测试字符串”,“is”也不是重复的字符串吗?这些字符串必须以某种方式清晰地分开吗? - Dmytro
2
@HansPassant:谢谢。现在我的头疼了。 - Robert Harvey
3
这似乎没有完全说明清楚,但它看起来不像是 stackoverflow.com/q/9424379 的重复。这个问题要求删除重复的子字符串("abcabc xx abcabc" -> "abc x abc"),而另一个问题则要求删除重复的单词("abcabc xx abcabc" -> "abcabc xx")。另一个问题中的解决方案(split().distinct().join())对于这个问题不起作用。 - Rasmus Faber
显示剩余4条评论
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));
        }
    }
}

谢谢,我明天会试一下。 - msbg
这将把“test”转换为“tes”。 - bwdeng
显然,如果我有注释,那么它是一个单词,意味着它将删除单词中重复的字符。而如果它是一个句子,那么它将根据相同的大小写(大写和小写)删除重复的单词。 - Arunkumar Chandrasekaran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接