小算法 – 将一个字符串分割成等长的几段

By | January 31, 2007

将一个string分成等长的几分
例如,SplitStringIntoMultipart( "abcdefgh", 3 );
会返回 "abc", "def", "gh"

public static string[] SplitStringIntoMultipart( string input , int eachCount )
{
    if( input.Length == 0 )
        return new string[0];
    if( input.Length <= eachCount )
        return new string[1]{input};
    int partNum;
    if( input.Length % eachCount == 0 )
        partNum = input.Length / eachCount;
    else
        partNum = input.Length / eachCount + 1;

    string[] result = new string[partNum];
    for( int i = 0; i < partNum - 1; i++ )
        result[i] = input.Substring( i * eachCount, eachCount);

    result[partNum-1] = input.Substring( ( partNum - 1 ) * eachCount );
    return result;
}