Coder Perfect

In C#, inserting a newline into a string

Problem

I have a piece of string.

string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";

Every time the “@” symbol appears in the string, I need to add a newline.

This is what my output should look like.

fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@

Asked by balaweblog

Solution #1

Make use of the environment. In any string, you can insert a newline wherever you choose. Consider the following scenario:

string text = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";

text = text.Replace("@", "@" + System.Environment.NewLine);

Answered by Christian C. Salvadó

Solution #2

After the @ symbol, you can add a new line character as follows:

string newString = oldString.Replace("@", "@\n");  

In the Environment Class, you can also use the NewLine attribute (I think it is Environment).

Answered by Jason

Solution #3

The preceding answers come near, but you’d want str to meet the true requirement that the @ sign stay close. Replace(“@”, “@” + System.Environment.NewLine) with “@”, “@” + System.Environment.NewLine). The @ sign will be preserved, and the proper newline character(s) for the current platform will be added.

Answered by Marcus Griep

Solution #4

Then simply change the previous responses to:

Console.Write(strToProcess.Replace("@", "@" + Environment.NewLine));

If you don’t want the text file to have newlines, don’t save it.

Answered by Benjamin Autin

Solution #5

A simple string replacement will suffice. Take a look at the following example program:

using System;

namespace NewLineThingy
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
            str = str.Replace("@", "@" + Environment.NewLine);
            Console.WriteLine(str);
            Console.ReadKey();
        }
    }
}

Answered by Jason Jackson

Post is based on https://stackoverflow.com/questions/224236/adding-a-newline-into-a-string-in-c-sharp