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

标签 c# .net string linq

我想做的是获取一个字符串并返回所有可能的长度大于 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/

相关文章:

c# - 从 DLL 调用函数?

c# - 从数据库加载大块数据时如何避免 OutOfMemoryException?

.net - 头与 WebClient?

c# - 集成测试详细

c - 从 C 字符串中去除第一个和最后一个字符

c# - 如何使用 Entity Framework 6更新相关数据

c# - 为 JWT 生成 key ?

javascript - 在 HTML5 Javascript 中将 BlobBuilder 转换为字符串

java - 从 Android 接收 Base64 编码的字符串到 C# 应用程序

c# - 如何在 EF 中批量更新