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

本文关键字:字符串 分解 有没有 方法 一种 | 更新日期: 2023-09-27 18:22:18

从下面的代码片段中,我要做的应该是显而易见的。

    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('=')是打印它的内容。

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

您可以使用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());
} 

您可以使用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));