gpt4 book ai didi

c# - 如何找到字符串中所有可能的子串?

转载 作者:可可西里 更新时间:2023-11-01 09:01:19 26 4
gpt4 key购买 nike

我想做的是获取一个字符串并返回所有可能的长度大于 2 的子字符串。因此使用 welcome 示例:

we
el
lc
co
me
wel
elc
lco
com
ome
welc
elco
lcom
come
and so on.....

我能想到的唯一方法是这样的(完全未经测试):

for (int i = 0; i < word.Length; i++) //i is starting position
{
for (int j = 2; j + i < word.Length; j++) //j is number of characters to get
{
wordList.Add(word.SubString(i, j));
}
}

但我想知道是否有我不知道的更好的方法(可能使用 LINQ)?

最佳答案

这种简单易读的方法怎么样?

var text = "welcome";

var query =
from i in Enumerable.Range(0, text.Length)
from j in Enumerable.Range(0, text.Length - i + 1)
where j >= 2
select text.Substring(i, j);

它产生:

we 
wel
welc
welco
welcom
welcome
el
elc
elco
elcom
elcome
lc
lco
lcom
lcome
co
com
come
om
ome
me

关于c# - 如何找到字符串中所有可能的子串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10712903/

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