每n个字符插入C#换行符

11

假设我有一个包含文本"THIS IS A TEST"的字符串。我该如何在每n个字符处分割它?例如,如果n为10,则应显示:

"THIS IS A "
"TEST"

..你们明白我的意思。原因是我希望将一行很长的文本拆分成较小的文本行,有点像自动换行的功能。我认为可以使用string.Split()来实现,但我不知道如何操作,感到困惑。

谢谢任何帮助。


1
可能是C#将字符串拆分为大小均为4的相等块的重复问题。 - Rune FS
这个回答解决了你的问题吗?将字符串分割成特定大小的块 - Magnetron
这个回答解决了你的问题吗?如何在每N个字符/数字处拆分字符串/数字? - StayOnTarget
6个回答

26

我们可以借鉴代码评审中我的答案的实现方法。这个方法可以在每个n个字符处插入一个换行符:

public static string SpliceText(string text, int lineLength) {
  return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);
}

编辑:
要返回一个字符串数组:

public static string[] SpliceText(string text, int lineLength) {
  return Regex.Matches(text, ".{1," + lineLength + "}").Cast<Match>().Select(m => m.Value).ToArray();
}

4
也许这可以用来高效处理极大的文件:
public IEnumerable<string> GetChunks(this string sourceString, int chunkLength)
{  
    using(var sr = new StringReader(sourceString))
    {
        var buffer = new char[chunkLength];
        int read;
        while((read= sr.Read(buffer, 0, chunkLength)) == chunkLength)
        {
            yield return new string(buffer, 0, read);
        }        
    }
}

实际上,这对于任何TextReader都适用。 StreamReader是最常用的TextReader。您可以处理非常大的文本文件(IIS日志文件,SharePoint日志文件等),而无需加载整个文件,而是逐行读取。


1
这个想法很好,但是如果 source.Length 不是 chunkLength 的倍数,这种方法是否会漏掉最后的字符? - Jack Miller
如果您想读取所有字符串(包括长度小于“chunkLength”的最后一个字符串),只需使用以下条件:while ((read = sr.Read(buffer, 0, chunkLength)) !=0) - 我零0七

2

您应该能够使用正则表达式来完成此操作。以下是一个示例:

//in this case n = 10 - adjust as needed
List<string> groups = (from Match m in Regex.Matches(str, ".{1,10}") 
                       select m.Value).ToList();

string newString = String.Join(Environment.NewLine, lst.ToArray());

请参考此问题以获取详细信息:
将字符串分成相同大小的块


1

也许不是最优的方式,但是不需要使用正则表达式:

string test = "my awesome line of text which will be split every n characters";
int nInterval = 10;
string res = String.Concat(test.Select((c, i) => i > 0 && (i % nInterval) == 0 ? c.ToString() + Environment.NewLine : c.ToString()));

最好使用String.Concat()而不是使用空字符串连接。 - Jeff Mercado

1

在进行代码审查后回到这里,还有另一种方法可以不使用 Regex 来实现相同的功能。

public static IEnumerable<string> SplitText(string text, int length)
{
    for (int i = 0; i < text.Length; i += length)
    {
        yield return text.Substring(i, Math.Min(length, text.Length - i));  
    }
}

0

我刚写的一些代码:

string[] SplitByLength(string line, int len, int IsB64=0) {

    int i;

    if (IsB64 == 1) {
        // Only Allow Base64 Line Lengths without '=' padding
        int mod64 = (len % 4);
        if (mod64 != 0) {
            len = len + (4 - mod64);
        }
    }

    int parts = line.Length / len;
    int frac  = line.Length % len;
    int extra = 0;
    if (frac != 0) {
        extra = 1;
    }
   
    string[] oline = new string[parts + extra];
   
    for(i=0; i < parts; i++) {
        oline[i] = line.Substring(0, len);
        line     = line.Substring(len);
    }
   
    if (extra == 1) {
        oline[i] = line;
    }
    return oline;
}

string CRSplitByLength(string line, int len, int IsB64 = 0)
{
    string[] lines = SplitByLength(line, len, IsB64);
    return string.Join(System.Environment.NewLine, lines);
}

string m = "1234567890abcdefghijklmnopqrstuvwxhyz";

string[] r = SplitByLength(m, 6, 0);

foreach (string item in r) {
    Console.WriteLine("{0}", item);
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接