Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

닌자고양이

[C#] 문자열을 특정 길이(chunk size)로 쪼개기 본문

C# .NET

[C#] 문자열을 특정 길이(chunk size)로 쪼개기

닌자고양이 2020. 9. 18. 22:51

Linq 사용

string[] Split(string str, int len)
{
    var chunks = Enumerable.Range(0, (str.Length + len - 1) / len);
    return chunks.Select(p => str.Substring(p * len, Math.Min(str.Length - p * len, len))).ToArray();
}

 

반복문 사용

string[] Split(string str, int len)
{
    int i, count = (str.Length + len - 1) / len;
    var arr = new string[count];

    for (i = 0; i < count - 1; i++)
        arr[i] = str.Substring(i * len, len);

    arr[i] = str.Substring(i * len);
    return arr;
}

 

Comments