74

How do I replace \n with empty space?

I get an empty literal error if I do this:

string temp = mystring.Replace('\n', '');
2
  • I should add that string temp = mystring.Replace("\n", ""); doesn't achieve anything Commented Mar 16, 2009 at 18:57
  • 6
    also, doesn't really matter but instead of "" you could use string.Empty. it makes me feel better =) Commented Mar 16, 2009 at 23:38

12 Answers 12

128

String.Replace('\n', '') doesn't work because '' is not a valid character literal.

If you use the String.Replace(string, string) override, it should work.

string temp = mystring.Replace("\n", "");
Sign up to request clarification or add additional context in comments.

7 Comments

It must, otherwise you are missing the \r of the new line or not properly storing the returned value from Replace.
it turned out that the string contained \r, so I am replacing both: replace("\n", ""); replace("\r", "");
@sarsnake is probably failing to notice the use of double quotes for the string overload.
You should always use String.Empty instead of ""
Good question (or point?)... Don't be so literal, that's why. ;) String.Empty vs. "" isn't really important (or worth debating) HOWEVER someValue == MyStaticValues.SomeMeaning vs someValue == "SomeMeaning" IS important and worth debating. Magic strings are harder to maintain and less readable so use constants and static values to elegantly and expressively represent your meanings. E.G. Colors.White vs #FFFFFF.
|
17

As replacing "\n" with "" doesn't give you the result that you want, that means that what you should replace is actually not "\n", but some other character combination.

One possibility is that what you should replace is the "\r\n" character combination, which is the newline code in a Windows system. If you replace only the "\n" (line feed) character it will leave the "\r" (carriage return) character, which still may be interpreted as a line break, depending on how you display the string.

If the source of the string is system specific you should use that specific string, otherwise you should use Environment.NewLine to get the newline character combination for the current system.

string temp = mystring.Replace("\r\n", string.Empty);

or:

string temp = mystring.Replace(Environment.NewLine, string.Empty);

Comments

4

This should work.

string temp = mystring.Replace("\n", "");

Are you sure there are actual \n new lines in your original string?

Comments

4
string temp = mystring.Replace("\n", string.Empty).Replace("\r", string.Empty);

Obviously, this removes both '\n' and '\r' and is as simple as I know how to do it.

Comments

2

If you use

string temp = mystring.Replace("\r\n", "").Replace("\n", "");

then you won't have to worry about where your string is coming from.

1 Comment

Shouldn't that be mystring.Replace("\r\n", "").Replace("\n", "") ? If you replace the \n with "", then "\r\n" becomes "\r" and "\r\n" won't match anything.
1

One caveat: in .NET the linefeed is "\r\n". So if you're loading your text from a file, you might have to use that instead of just "\n"

edit> as samuel pointed out in the comments, "\r\n" is not .NET specific, but is windows specific.

6 Comments

-1, "\r\n" is not from .NET. It's from Windows, use Environment.NewLine to find the newline sequence for the environment (Windows/Linux/Other).
Either way, the point still stands. "\n" is not necessarily the linefeed.
And "\n" is not not necessarily the linefeed. Since the poster has it, one must infer that it is the linefeed they are looking for.
For such an inference to be valid and true the premise (in this case, that \n is what the poster wants and needs) must also be true. If that were the case, it'd work just fine as it is.
Stop arguing about \r\n and use Environment.NewLine
|
1

What about creating an Extension Method like this....

 public static string ReplaceTHAT(this string s)
 {
    return s.Replace("\n\r", "");
 }

And then when you want to replace that wherever you want you can do this.

s.ReplaceTHAT();

Best Regards!

1 Comment

+1 for increasing readability and reusability by suggesting Extension Method, but the name of the method could be something more descriptinve, like ReplaceNewLine()
1

Here is your exact answer...

const char LineFeed = '\n'; // #10
string temp = new System.Text.RegularExpressions.Regex(
                  LineFeed
              ).Replace(mystring, string.Empty);

But this one is much better... Specially if you are trying to split the lines (you may also use it with Split)

const char CarriageReturn = '\r'; // #13
const char LineFeed = '\n'; // #10
string temp = new System.Text.RegularExpressions.Regex(
                  string.Format("{0}?{1}", CarriageReturn, LineFeed)
              ).Replace(mystring, string.Empty);

3 Comments

What's the overhead on using a regex for a trivial replacement?
it does replaces both "\r\n" and "\n" so both works (double replace or above)
too much needless complication and extra code, cilerler. :( string temp = mystring.Replace("\n", string.Empty).Replace("\r", string.Empty); is so much faster and simpler.
0
string temp = mystring.Replace("\n", " ");

1 Comment

he does not want it replaced with a space. we wanted it replaced with string.Empty.
0

@gnomixa - What do you mean in your comment about not achieving anything? The following works for me in VS2005.

If your goal is to remove the newline characters, thereby shortening the string, look at this:

        string originalStringWithNewline = "12\n345"; // length is 6
        System.Diagnostics.Debug.Assert(originalStringWithNewline.Length == 6);
        string newStringWithoutNewline = originalStringWithNewline.Replace("\n", ""); // new length is 5
        System.Diagnostics.Debug.Assert(newStringWithoutNewline.Length == 5);

If your goal is to replace the newline characters with a space character, leaving the string length the same, look at this example:

        string originalStringWithNewline = "12\n345"; // length is 6
        System.Diagnostics.Debug.Assert(originalStringWithNewline.Length == 6);
        string newStringWithoutNewline = originalStringWithNewline.Replace("\n", " "); // new length is still 6
        System.Diagnostics.Debug.Assert(newStringWithoutNewline.Length == 6);

And you have to replace single-character strings instead of characters because '' is not a valid character to be passed to Replace(string,char)

Comments

0

I know this is an old post but I'd like to add my method.

public static string Replace(string text, string[] toReplace, string replaceWith)
    {
        foreach (string str in toReplace)
           text = text.Replace(str, replaceWith);

        return text;
    }

Example usage:

string newText = Replace("This is an \r\n \n an example.", new string[] { "\r\n", "\n" }, "");

Comments

0

Found on Bytes.com:

string temp = mystring.Replace('\n', '\0');// '\0' represents an empty char

3 Comments

'\0' is NULL not empty ... >_> and yes I know this is old but that's some dangerous info right there
i second and third dten's rebuttal. '\0' is a character. the name of the character is sometimes called NIL or even rarely 'empty char', but this use of 'empty' is misleading and confusing to people who don't know any better. '\0' = character 0 which is another character just like any other characters. but each character has a function. when you need a character that you can treat as an empty character then you can use '\0'. i do sometimes. but just a one-line answer that says this is an empty character really is 'dangerous info' as dten warns.
null and empty and '\0' are usually used to represent 3 different values that are not equivalent (but they are related). null is a string value which essentially says 'my value is missing' or 'not here'. empty means the value exists, but has no characters--it's length is zero. and '\0' is not a string. a string can have one character which can be '\0' or any other character value. but it is true that some people call '\0' a NIL char, NULL char, or empty character. so beware in code. in c#, null != string.Empty, null != '\0' and string.Empty != '\0'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.