在python中使用一些代码按顺序输出字符串的特殊组合: 如何在c#
上做到这一点def getOrderCombinations(me):
l = len(me)
looped = me+ me
for start in range(0, l):
for length in range(1, l):
print(looped[start:start+length])
which gives:
>>> getOrderCombinations("ABCD")
A
AB
ABC
B
BC
BCD
C
CD
CDA
D
DA
DAB
我在尝试
public static string[] Combinations(string str)
{
if (str.Length == 1)
return new string[] { str };
char c = str[str.Length - 1];
//here I was planning to make recursion
string[] returnArray = Combinations(str.Substring(0, str.Length - 1));
// keep final string combinations
List<string> finalArray = new List<string>();
//how to loop correctly and avoid getting all combinations
foreach (string s in returnArray)
finalArray.Add(s);
finalArray.Add(c.ToString());
}
对于字符串'ABCD',输出应为'A','B','C','D','AB','BC','CD','DA','ABC','BCD ','CDA',DAB'。因此,字符串长度n的可能子串的数量将总是n *(n-1)。
如何在c#上进行操作?
答案 0 :(得分:5)
在python中实现它的方式有什么问题?直接端口应该可以很好地工作,我想:
public IEnumerable<string> GetOrderCombinations(string me)
{
int l = me.Length ;
string looped = me + me ;
for ( int start = 0 ; start < l ; ++start )
{
for ( int length = 1 ; length < l ; ++length )
{
yield return looped.Substring( start , length ) ;
}
}
}
你甚至可以把它变成Linq one-liner,几乎是Python实现的直接端口:
public static IEnumerable<string> GetOrderCombinations( string me )
{
string looped = me + me;
return Enumerable
.Range(0,me.Length)
.SelectMany( x => Enumerable.Range(1,me.Length) , looped.Substring )
;
}
答案 1 :(得分:3)
编辑:请考虑以下代码......
string str = "LEQN";
List<char> characters = str.ToCharArray().ToList();
List<string> combinations = new List<string>();
for (int i = 0; i < characters.Count; i++)
{
int combCount = 1;
string comb = characters[i].ToString();
combinations.Add(comb);
for (int j = 1; j < characters.Count - 1; j++)
{
int k = i + j;
if (k >= characters.Count)
{
k = k - characters.Count;
}
comb += characters[k];
combinations.Add(comb);
combCount++;
}
}
祝你好运!
以下是上述代码的输出......
答案 2 :(得分:1)
这应该有效:致电 - &gt; GetCombinations( “ABCD”);
List<string> allcombinations = new List<string>();
public void GetCombinations(string input)
{
GetCombinations(1, input);
}
private void GetCombinations(int combLength, string input)
{
string current = string.Empty;
for (int index = 0; index < input.Length; ++index)
{
if (index + combLength <= input.Length)
{
current = input.Substring(index, combLength);
allcombinations.Add(current);
}
else
{
int leftOver = input.Length - index;
current = input.Substring(index, leftOver);
current += input.Substring(0, combLength - leftOver);
allcombinations.Add(current);
}
}
if (combLength < input.Length - 1)
{
GetCombinations(++combLength, input);
}
}