gpt4 book ai didi

c# - 如何将字符串数组拆分为新的字符串数组并删除重复项

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:03 25 4
gpt4 key购买 nike

我有一个字符串,但我不知道它的项目数。我想将此字符串数组拆分为一个新数组。之后,我需要删除重复的项目,如下例所示。

例如在下面:单词“hi”和“friends”出现两次,但我们在第二个数组中写入一次,它并不总是必须超过两次,有时超过 3 次或更多,单词“hi”和“ friend ”只是例如,也许其他词会出现两次或多次)。

例如;

string[] myString = {"hello friends", "hi guys", "hi friends", "how are", "123654 u?", "today man", "! ?", "maybe tomorrow", "5 2-", "99 1585126", "(/&&/& _____"};

我想将它拆分成一个新的字符串数组(根据空格字符);
string[] new = {"hello", "friends", "hi", "guys", "how", "are", "123654", "u?", "today", "man", "!", "?", "maybe", "tomorrow","5" ,"2-" ,"99", "1585126", "/&&/&", "_____"} ;

最佳答案

使用SelectManyDistinct :

string[] newArray = myString.SelectMany(s => s.Split(' ')).Distinct().ToArray();

如果您想以不区分大小写的方式进行比较,请将适当的比较器传递给 Distinct :
string[] newArray = myString.SelectMany(s => s.Split(' ')).Distinct(StringComparer.InvariantCultureIgnoreCase).ToArray();

关于c# - 如何将字符串数组拆分为新的字符串数组并删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54291504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com