如何从字符串中删除重复的子字符串
本文关键字:字符串 删除 | 更新日期: 2023-09-27 17:50:23
如何在c#中从字符串中删除任何重复的子字符串?例如,在这个字符串中:
This is a test test string
重复的" test"将被删除,创建结果:
This is a test string
或
shift+shift+shift+shift+d
"shift+shift+shift+"将被删除,从而产生
shift+d
我希望通过你的问题本身通过改变句子来删除重复的单词和单词重复的字符。
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));
}
}
}