在C#.NET中有一种方法可以将字符串分解为固定长度的子字符串吗?

时间:2015-11-17 15:54:55

标签: c# .net algorithm

我尝试做的事情应该从下面的代码片段中明显看出来。

    public static void PrintTable ( string[][] cells )
    {
        // Outputs content in cells matrix like 

        // =========================================
        //  cells[0][0]   | cells[0][1]
        // -----------------------------------------
        //  cells[1][0]   | cells[1][1]
        // -----------------------------------------
        //  cells[2][0]   | cells[2][1]
        //                .
        //                .
        // -----------------------------------------
        //  cells[n-1][0] | cells[n-1][1]
        //  ========================================

        // Each cell must be able to hold at least 1 character inside 
        // 1 space of padding on the left and right

        OutputFormatter.PrintChars('=');
        int colOneWidth = Math.Max(cells.Max(c => c[0].Length) + 2, OutputFormatter._outputMaxLength - 7);
        int colTwoWidth = OutputFormatter._outputMaxLength - colOneWidth - 1;
        foreach ( string[] row in cells )
        {
            string[] colOneParts = ... (get row[0] broken down into pieces of width colOneWidth with 1 space of padding on each side)
            string[] colTwoParts = ... (get row[1] broken down into pieces of width colTwoWidth with 1 space of padding on each side)
            // ... 
        }

        // ... 
        OutputFormatter.PrintChars('=');
    }

对于我需要将string分解为固定长度的子string的部分,.NET库是否有任何方法可以让我的生活更轻松?这样我可以在多行上获取内容,例如

====================================================
 This is only on 1 line | As you can see, this is o
                        | n multiple lines.
----------------------------------------------------
 This only 1 line too   | This guy might go all the
                        | way onto 3 lines if I mak
                        | e him long enough
====================================================

作为参考,OutputFormatter._outputMaxLength是表格的宽度,即====================================================的长度,而PrintChars('=')是打印的宽度。

2 个答案:

答案 0 :(得分:2)

您可以使用String.Take(numOfChars)

string line;
var numOfChars = 30;
var input = "Quite long text to break into 30 characters";
while ((line = new String(input.Take(numOfChars).ToArray())).Any())
{
    Console.WriteLine(line);
    input = new String(input.Skip(numOfChars).ToArray());
} 

答案 1 :(得分:2)

您可以使用 Linq

  int size = 4; // 30 in your case
  String sample = "ABCDEFGHI";

  var chunks = Enumerable
    .Range(0, sample.Length / size + (sample.Length / size == 0 ? 0 : 1))
    .Select(i => sample.Substring(i * size, Math.Min(size, sample.Length - i * size)));

测试

   // ABCD
   // EFGH
   // I
   Console.Write(String.Join(Environment.NewLine, chunks));