Easiest way to split a string on newlines in .NET?

后端 未结 16 2492
抹茶落季
抹茶落季 2020-11-22 06:57

I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a ne

16条回答
  •  误落风尘
    2020-11-22 07:40

    Examples here are great and helped me with a current "challenge" to split RSA-keys to be presented in a more readable way. Based on Steve Coopers solution:

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

    Presenting a RSA-key with 33 chars width and quotes are then simply

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

    Output:

    Hopefully someone find it usefull...

提交回复
热议问题