我是 C# 的新手,遇到了一些问题。
我有 2 个列表、2 个字符串和一个 getCombinations(string) 方法 将字符串的所有组合作为列表返回;
我如何验证 subjectStrings 元素是否不存在 StartWith && !EndsWith && !Contains(或 !StartWith && !EndsWith && Contains 等) 对于 startswithString、endswithString 和 containsString 的每个组合?
这是我在 StartWith && !EndsWith 中的代码 (如果你想看到它运行:http://ideone.com/y8JZkK)
using System;
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
List<string> validatedStrings = new List<string>();
List<string> subjectStrings = new List<string>()
{
"con", "cot", "eon", "net", "not", "one", "ten", "toe", "ton",
"cent", "cone", "conn", "cote", "neon", "none", "note", "once", "tone",
"cento", "conte", "nonce", "nonet", "oncet", "tenon", "tonne",
"nocent","concent", "connect"
}; //got a more longer wordlist
string startswithString = "co";
string endswithString = "et";
foreach(var z in subjectStrings)
{
bool valid = false;
foreach(var a in getCombinations(startswithString))
{
foreach(var b in getCombinations(endswithString))
{
if(z.StartsWith(a) && !z.EndsWith(b))
{
valid = true;
break;
}
}
if(valid)
{
break;
}
}
if(valid)
{
validatedStrings.Add(z);
}
}
foreach(var a in validatedStrings)
{
Console.WriteLine(a);
}
Console.WriteLine("\nDone");
}
static List<string> getCombinations(string s)
{
//Code that calculates combinations
return Permutations.Permutate(s);
}
}
public class Permutations
{
private static List<List<string>> allCombinations;
private static void CalculateCombinations(string word, List<string> temp)
{
if (temp.Count == word.Length)
{
List<string> clone = temp.ToList();
if (clone.Distinct().Count() == clone.Count)
{
allCombinations.Add(clone);
}
return;
}
for (int i = 0; i < word.Length; i++)
{
temp.Add(word[i].ToString());
CalculateCombinations(word, temp);
temp.RemoveAt(temp.Count - 1);
}
}
public static List<string> Permutate(string str)
{
allCombinations = new List<List<string>>();
CalculateCombinations(str, new List<string>());
List<string> combinations = new List<string>();
foreach(var a in allCombinations)
{
string c = "";
foreach(var b in a)
{
c+=b;
}
combinations.Add(c);
}
return combinations;
}
}
输出:
con
cot
cone
conn
cote <<<
conte <<<
concent
connect
Done
如果(z.StartsWith(a) && !z.EndsWith(b)) var b 可以是“et”和“te”,但 cote 和 conte 以“te”结尾, 为什么它仍然添加到我的验证字符串中?
提前致谢。
最佳答案
z.StartsWith(a) && !z.EndsWith(b)
检查下面的组合
z ="cote"
a ="co"
b ="te"
所以 z 以“co”开头且 z 不以“te”结尾,您的条件通过并且 cote
将添加到列表中
我会尝试如下
var sw =getCombinations(startswithString);
var ew = getCombinations(endswithString);
var result = subjectStrings.Where(z=>
sw.Any(x=>z.StartsWith(x) &&
!ew.Any(y=>z.EndsWith(y))))
.ToList();
输出:
con
cot
cone
conn
concent
connect
关于C# (String.StartsWith && !String.EndsWith && !String.Contains) 使用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19341962/