我正在尝试将字符串“增长”到所需的长度(即“ABCDE”,所需的长度为 7,填充变为“--ABCDE”、“-A-BCDE”、“-AB-CDE”...... ..,“ABCDE--”)。
当我尝试使用以下代码将“ABCDEFGH”填充到长度 16 时,代码将永远运行。
/// <summary>
/// Pad a str to desired length
/// </summary>
/// <param name="s"></param>
/// <param name="length"></param>
/// <param name="pad"></param>
/// <param name="Padded"></param>
public static void PadToLength(string s, int length, char pad, ref List<string> Padded)
{
if (s.Length == length)
{
Padded.Add(s);
return;
}
else if (s.Length > length)
{
return;
}
else
{
List<int> pos = GetExceptPos(s, pad.ToString());
pos.Sort();
int count = -1;
foreach (int p in pos)
{
count++;
// Pad left
string leftPadStr = s.Substring(0, p) + pad + s.Substring(p);
PadToLength(leftPadStr, length, pad, ref Padded);
// Pad right at the last pos
if (count == pos.Count - 1)
{
string rightPadStr = s + pad;
PadToLength(rightPadStr, length, pad, ref Padded);
}
}
}
}
/// <summary>
/// Find indexes for elements different from target str
/// </summary>
/// <param name="str"></param>
/// <param name="excludeStr"></param>
/// <returns></returns>
private static List<int> GetExceptPos(string str, string excludeStr)
{
List<int> allIndexes = new List<int>();
for (int i = 0; i < str.Length; i++)
{
allIndexes.Add(i);
}
return allIndexes.Except(str.IndexesOf(excludeStr)).ToList();
}
任何建议将不胜感激。谢谢。