c# - C#.NET 中有没有办法将字符串分解为固定长度的子字符串?

标签 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('=');
    }

.NET 库是否有任何方法可以让我的生活变得轻松,因为我需要分解 string进入子string s 是固定长度的吗?这样我就可以在多行上获取内容,例如

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

最佳答案

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

关于c# - C#.NET 中有没有办法将字符串分解为固定长度的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33761371/

相关文章:

algorithm - 为什么贝尔曼福特算法中的 |V|-1 次迭代可以保证最短路径?

python - 从消耗时间的项目和不消耗时间但仍需要绘制空间的项目生成基于时间线的线性表示

javascript - 动态调整 HTML div 对象和子元素的大小

c# - 面板控件中的对齐按钮

c# - 布局从页面提取数据的最佳方式是什么?

c# - 在 VS2008 中找不到 System.Web.Hosting

c# - c# 100个应用同时写入日志时如何实现同步

.net - 加密 web.config 毫无意义吗?

r - 是否有一种有效的算法来创建这种类型的时间表?

c# - IIS/C# 网站与 Tomcat/Java 网站共享身份验证 - 相同的顶级 URL