c# - 在一定数量的字符和换行符之后分割字符串。在 C# 中

标签 c# string substring

背景:我正在获取大字符串(500-5000 个字符)并将它们放入 PPTX 文件中。我的幻灯片只有足够的空间容纳每张幻灯片大约 1000 个字符。我想在幻灯片写满后分割文本并继续下一张幻灯片。据我所知,如果文本已经在幻灯片/文本框之外,则无法(非常肯定)检查幻灯片(我正在使用“OpenXML SDK 与“Open-XML PowerTools”结合使用)。

到目前为止的过程:我设法编写了一种方法,可以在正好 1000 个字符之后分割字符串,而当 maxLength 小于 1000 个字符时不会触发错误(就像 Substring(startIndex, maxLength 发生的那样) ))。这是我的截断方法:

public static string Truncate(string text, int startIndex, int maxLength)
        {

            if (string.IsNullOrEmpty(text)) return text;
            if (text.Length > startIndex + maxLength)
            {
                return text.Substring(startIndex, maxLength) + "-";
            }
            return text.Substring(startIndex);
        }

有问题:现在的问题是有些字符串有很多换行符,而另一些字符串则很少或没有换行符。这导致一些弦需要很大的高度并且太大而无法放入幻灯片中。

可能的想法:我考虑过通过计算换行符来估计字符串高度,并将 30 个字符添加到每个换行符的字符数中。这给出了更精确的近似值。 (一行充满字符通常包含大约 50 个字符,但有时换行符位于行的中间,所以我认为 +30 个字符是一个不错的猜测)。到目前为止,这是我的方法:

public int CountCharacters(string text)
{
    var numLines = text.Length;
    numLines += (text.Split('\n').Length) * 30;
    return numLines;
}

结果问题:在达到 1000 后,考虑换行符,我现在如何组合这些方法来分割字符串?或者这到底是错误的做法?

最佳答案

像这样怎么样:

        string test; //your input string
        int j;  //variable that holds the slide content length
        int max_lines = 10;  //desired maximum amount of lines per slide
        int max_characters = 1000; //desired maximum amount of characters
        char[] input = test.ToCharArray();  //convert input string into an array of characters
        string slide_content;    //variable that will hold the output of each single slide

        while (input.Length > 0)
        {
            //reset slide content and length
            slide_content = string.Empty;
            j = 0;

            //loop through the input string and get a 'j' amount of characters
            while ((slide_content.Split('\n').Length < max_lines) && (j < max_characters))
            {
                j = j + 1;
                slide_content = new string(input.Take(j).ToArray());
            }

            //Output slide content
            Console.WriteLine(slide_content);
            Console.WriteLine("=================== END OF THE SLIDE =====================");          

            //Remove the previous slide content from the input string
            input = input.Skip(j).ToArray();       
        }

        Console.Read();

关于c# - 在一定数量的字符和换行符之后分割字符串。在 C# 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40383511/

相关文章:

c# - 重用 ICryptoTransform 对象

c# - 使用泛型避免缓存不同类型时的强制转换

python - 如何在python中删除路径前缀?

C:评估字符串的一部分

mysql - 将 char 插入 MySQL varchar 值

c# - 如何在 C# 中引发事件 - 最佳方法

c# - 使用 Linq 从树中获取具有特定属性的所有对象

mysql - SQL - 提取可变长度字符串的数字部分

ruby - 如何使用 Ruby 删除字符串中某个字符后的子字符串?

c++ - 递归函数生成不包含两个相邻相同子串的字符串c++