我想做的是取一个字符串并返回大于长度为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),我不知道?
答案 0 :(得分:13)
这是一种简单易读的方法吗?
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
答案 1 :(得分:4)
这个LINQ解决方案应该有效:
var str = "welcome";
var items = Enumerable
.Range(0, str.Length)
.SelectMany(i => Enumerable.Range(2, str.Length-i-1).Select(j => str.Substring(i, j)))
.Distinct()
.OrderBy(s => s.Length);
foreach (var s in items) {
Console.WriteLine(s);
}
答案 2 :(得分:0)
代码如下:
internal static List<string> GetAllSubstring(String mainString)
{
try
{
var stringList = new List<string>();
if(!string.IsNullOrEmpty(mainString))
{
for (int i = 0; i < mainString.Length; i++) //i is starting position
{
for (int j = 2; j + i < mainString.Length; j++) //j is number of characters to get
{
if(!stringList.Contains(mainString.Substring(i, j)))
{
stringList.Add(mainString.Substring(i, j));
}
}
}
}
return stringList;
}
catch(Exception ex)
{
}
return null;
}