gpt4 book ai didi

c# - 从字符串中拆分并删除重复项

转载 作者:行者123 更新时间:2023-11-30 13:17:42 25 4
gpt4 key购买 nike

我想拆分给定的字符串并从该字符串中删除重复项。就像我有以下字符串:

This is my first post in stack overflow, I am very new in development and I did not have much more idea about the how to post the question.

现在我想用空格拆分整个字符串,新数组将没有重复项。

我该怎么做?

最佳答案

"This is my first post in stack overflow, I am very new in development and I did not have much more idea about the how to post the question."
.Split() // splits using all white space characters as delimiters
.Where(x => x != string.Empty) // removes an empty string if present (caused by multiple spaces next to each other)
.Distinct() // removes duplicates

Distinct()Where()是 LINQ 扩展方法,所以你必须有 using System.Linq;在你的源文件中。

以上代码将返回 IEnumerable<string> 的一个实例.您应该能够使用它执行所需的大多数操作。如果你真的需要一个数组,你可以追加.ToArray()声明。

关于c# - 从字符串中拆分并删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6715732/

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