我需要一个在c#中返回一个c#的函数。
该函数需要返回所有可能性,以便:
2-4个字符字母数字(a-z A-Z0-9)
你有什么目的来做一个快速生成功能吗?(需要快速生成)
发布于 2013-11-25 19:50:00
首先,如果你想把它作为一个列表,你肯定不会把它放进任何现有的内存中。大概是(58^10+58^9+58^8.字节数)。
但是,您可以尝试这样的方法:
// this generates all strings for characters 0-3 with lengths 2-3
List<string> result = GenerateStrings("0123", 2, 3);
private List<string> GenerateStrings(string allowedChars, int fromLength, int toLength)
{
List<string> strings = new List<string>();
int charsNum = allowedChars.Length;
for (int currentLength = fromLength; currentLength <= toLength; currentLength++)
{
// initialize array of indexes to generate individual characters
int[] indexes = new int[currentLength];
do
{
StringBuilder sb = new StringBuilder(currentLength);
// generate characters based on current index values
for (int charPosition = 0; charPosition < currentLength; charPosition++)
{
sb.Append(allowedChars[indexes[charPosition]]);
}
strings.Add(sb.ToString());
// until we can increment indexes array (still some character combinations available)
} while (IncrementIndex(indexes, charsNum - 1, currentLength - 1));
}
return strings;
}
/// <summary>
/// Have array of integer indexes such as [0,0,0] with valid values 0-9.
/// This function increments indexes from right by one with correct overflow handling,
/// such that value [0,0,3] is incremented to [0,0,4], value [0,2,9] to [0,3,0] etc.
/// </summary>
/// <returns>True if increment was successful, false if maximal value was reached.</returns>
private bool IncrementIndex(int[] indexes, int maxItemValue, int incrementFromPosition)
{
indexes[incrementFromPosition]++;
// check if current position overflow allowed range
if (indexes[incrementFromPosition] > maxItemValue)
{
if (incrementFromPosition == 0)
{
// we reached left-most position and can't increment more
return false;
}
indexes[incrementFromPosition] = 0;
// increment next position to the left
return IncrementIndex(indexes, maxItemValue, incrementFromPosition-1);
}
return true;
}
发布于 2013-11-25 19:43:14
尝尝这个
List lst =新List() { "a“、"b”、"c“、"d”、"e“、"f”、"g“、"h”};
List<string> newlst = (from p in lst
from q in lst
select p + q).ToList();
https://stackoverflow.com/questions/20201348
复制相似问题