字串拆成特定長度,下面提供兩個方式:
IEnumerable
/// <summary>
/// 字串拆成特定長度
/// </summary>
/// <param name="str">原始字串</param>
/// <param name="chunkSize">每個區塊的長度</param>
/// <returns></returns>
/// <example>
/// <code>
/// var s = Split("5275797574", 2);
/// </code>
/// </example>
/// <see href="https://www.ruyut.com/2021/08/CSharpStringSplit.html"/>
static IEnumerable<string> Split(string str, int chunkSize)
{
return Enumerable.Range(0, str.Length / chunkSize)
.Select(i => str.Substring(i * chunkSize, chunkSize));
}
假設你比較習慣字串陣列
/// <summary>
/// 字串拆成特定長度
/// </summary>
/// <param name="str">原始字串</param>
/// <param name="chunkSize">每個區塊的長度</param>
/// <returns></returns>
/// <example>
/// <code>
/// string[] s = Split("5275797574", 2);
/// </code>
/// </example>
/// <see href="https://www.ruyut.com/2021/08/CSharpStringSplit.html"/>
static string[] Split(string str, int chunkSize)
{
return Enumerable.Range(0, str.Length / chunkSize)
.Select(i => str.Substring(i * chunkSize, chunkSize)).ToArray();
}
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com