(未测试)
public static string Transform(string text)
{
// Insert null-check here. You may also want to trim the string.
var letters = text.Where(char.IsLetter).OrderBy(l => l).ToArray();
var numbers = text.Where(char.IsNumber).OrderBy(n => n).ToArray();
if (letters.Length != numbers.Length || (letters.Length + numbers.Length != text.Length))
throw new FormatException("Text must consist only of an equal number of letters and numbers.");
var zipped = letters.Zip(numbers, (l, n) => string.Concat(l, n));
return string.Concat(zipped.ToArray());
}
如果你在.NET 3.5中,你可以替换的压缩和解路线:
var zipped = Enumerable.Range(0, text.Length).Select(i => string.Concat(letters[i], numbers[i]));
来源
2010-09-02 12:33:43
Ani
如果输入是'abc1278d'会怎么样?或'a4b3c2d1'?你的例子并没有多大帮助,它看起来像'a1'是一个单一的字母... – Kobi 2010-09-02 12:25:11
澄清,abc1278d = a1b2c7d8和a4b3c2d1 = a1b2c3d4 - 抱歉。交替每个字母和数字。 – user234702 2010-09-02 12:26:50
你确定你总是有相同数量的数字和字母吗? – digEmAll 2010-09-02 12:30:18