我需要在. net中将字符串分割为换行符,我所知道的分割字符串的唯一方法是使用split方法。然而,这将不允许我(容易)在换行上分裂,那么最好的方法是什么?


当前回答

这里的示例非常棒,帮助我解决了当前的“挑战”,以一种更可读的方式分割rsa密钥。基于Steve Coopers的解决方案:

    string Splitstring(string txt, int n = 120, string AddBefore = "", string AddAfterExtra = "")
    {
        //Spit each string into a n-line length list of strings
        var Lines = Enumerable.Range(0, txt.Length / n).Select(i => txt.Substring(i * n, n)).ToList();
        
        //Check if there are any characters left after split, if so add the rest
        if(txt.Length > ((txt.Length / n)*n) )
            Lines.Add(txt.Substring((txt.Length/n)*n));

        //Create return text, with extras
        string txtReturn = "";
        foreach (string Line in Lines)
            txtReturn += AddBefore + Line + AddAfterExtra +  Environment.NewLine;
        return txtReturn;
    }

呈现一个具有33个字符宽度和引号的RSA-key是很简单的

Console.WriteLine(Splitstring(RSAPubKey, 33, "\"", "\""));

输出:

希望有人觉得它有用…

其他回答

好吧,实际上拆分应该做:

//Constructing string...
StringBuilder sb = new StringBuilder();
sb.AppendLine("first line");
sb.AppendLine("second line");
sb.AppendLine("third line");
string s = sb.ToString();
Console.WriteLine(s);

//Splitting multiline string into separate lines
string[] splitted = s.Split(new string[] {System.Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);

// Output (separate lines)
for( int i = 0; i < splitted.Count(); i++ )
{
    Console.WriteLine("{0}: {1}", i, splitted[i]);
}
using System.IO;

string textToSplit;

if (textToSplit != null)
{
    List<string> lines = new List<string>();
    using (StringReader reader = new StringReader(textToSplit))
    {
        for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
        {
            lines.Add(line);
        }
    }
}

要拆分一个字符串,你需要使用一个字符串数组的重载:

string[] lines = theText.Split(
    new string[] { Environment.NewLine },
    StringSplitOptions.None
);

编辑: 如果要处理文本中不同类型的换行符,可以使用匹配多个字符串的功能。这将正确地拆分任意类型的换行,并保留文本中的空行和空格:

string[] lines = theText.Split(
    new string[] { "\r\n", "\r", "\n" },
    StringSplitOptions.None
);
string[] lines = text.Split(
  Environment.NewLine.ToCharArray(), 
  StringSplitOptions.RemoveEmptyStrings);

RemoveEmptyStrings选项将确保由于\n跟在\r后面而没有空条目

(编辑以反映注释:)注意,它也会丢弃文本中的真正空行。这通常是我想要的,但这可能不是你的要求。

使用StringReader怎么样?

using (System.IO.StringReader reader = new System.IO.StringReader(input)) {
    string line = reader.ReadLine();
}