我是C#中的新手,我遇到了問題。C#(String.StartsWith &&!String.EndsWith &&!String.Contains)使用列表
我有2個列表,2個字符串和一個getCombinations(字符串)方法, 返回一個字符串的所有組合作爲列表;
如何驗證是否subjectStrings元素不 StartWith & &!的endsWith & &!包含(或!StartWith & &!的endsWith & &包含等) 爲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(一) (b)) var b可以是「et」和「te」,但cote和conte結尾是「te」, 爲什麼它仍然是添加在我驗證的字符串?
在此先感謝。
你可以使用遞歸函數請你提供更多的例子,我明白什麼該函數返回的輸出這樣的問題。 – saeed