C# C每n个字符换行一次

C# C每n个字符换行一次,c#,split,line,character,C#,Split,Line,Character,假设我有一个文本字符串:这是一个测试。我将如何每n个字符拆分一次?如果n是10,那么它会显示: "THIS IS A " "TEST" …你明白了。原因是我想把一个很大的行分割成更小的行,有点像换行。我想我可以用string.Split来做这个,但我不知道怎么做,我很困惑 如果您有任何帮助,我们将不胜感激。您应该能够为此使用正则表达式。以下是一个例子: //in this case n = 10 - adjust as needed List<string> groups = (f

假设我有一个文本字符串:这是一个测试。我将如何每n个字符拆分一次?如果n是10,那么它会显示:

"THIS IS A "
"TEST"
…你明白了。原因是我想把一个很大的行分割成更小的行,有点像换行。我想我可以用string.Split来做这个,但我不知道怎么做,我很困惑


如果您有任何帮助,我们将不胜感激。

您应该能够为此使用正则表达式。以下是一个例子:

//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());
有关详细信息,请参阅此问题:

让我们从代码审查中借用一个实现。这将每隔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();
}

可能不是最理想的方式,但没有正则表达式:

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()));

也许这可以用来有效地处理超大文件:

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);
        }        
    }
}

实际上,这适用于任何文本阅读器。StreamReader是最常用的文本阅读器。您可以处理非常大的文本文件IIS日志文件、SharePoint日志文件等,而不必加载整个文件,而是逐行读取。

在进行代码检查后,回到这一点,还有另一种方法可以不使用Regex执行相同的操作

可能的重复最好使用String.Concat,而不是带有空字符串的连接。
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));  
    }
}