你可以使用Linq的一點點,像這樣:
string Hyphenate(string str, int pos) {
return String.Join("-",
str.Select((c, i) => new { c, i })
.GroupBy(x => x.i/pos)
.Select(g => String.Join("", g.Select(x => x.c))));
}
或者這樣:
string Hyphenate(string str, int pos) {
return String.Join("-",
Enumerable.Range(0, (str.Length - 1)/pos + 1)
.Select(i => str.Substring(i * pos, Math.Min(str.Length - i * pos, pos))));
}
或者你可以使用正則表達式,像這樣:
string Hyphenate(string str, int pos) {
return String.Join("-", Regex.Split(str, @"(.{" + pos + "})")
.Where(s => s.Length > 0));
}
或者是這樣的:
string Hyphenate(string str, int pos) {
return String.Join("-", Regex.Split(str, @"(?<=\G.{" + pos + "})(?!$)"));
}
所有這些方法都將返回相同的結果:
Console.WriteLine(Hyphenate("abcdxy123z", 2)); // ab-cd-xy-12-3z
Console.WriteLine(Hyphenate("abcdxy123z", 3)); // abc-dxy-123-z
Console.WriteLine(Hyphenate("abcdxy123z", 4)); // abcd-xy12-3z
您遇到什麼問題需要幫助? –
那麼......每第三個角色? –
歡迎來到StackOverflow。您需要向我們提供您想要實現的具體細節,並且如果可能的話,您已經嘗試過的代碼。你需要的東西很不清楚,因爲你給了我們3個例子 - 全部6個字符長度 - 告訴我們字符數量可能會有所不同,但不告訴我們應該採取什麼格式 – freefaller