(未測試)
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