Question

How to remove \n in a string?

E.g.

  1. Input : string s = "\n1234"
  2. Output I want (but I can't achieve) : string s = "1234"

What I've tried (and failed) :

  1. s.Remove(0,1);
  2. s.Trim();

Additional notes :

I think \n counts as 1 char because, when I tried :

bool b = s[0]=='\n';

b = true.

Was it helpful?

Solution

Maybe not the fastes solution, but works:

string s = "\n1234".Replace("\n", String.Empty);

If the \n is only at the beginning or end of the string you can also use a "custom Trim":

string s = "\n1234".Trim('\n');

The '\n' should not be required as it is included in the default white-space characters, which are removed by Trim by default.

OTHER TIPS

You are not assigning the result back to string, otherwise your both Trim and Remove should work.

String is an immutable type, and its method doesn't modify the exiting string, instead they return a new string. So when you do s.Remove(0, 1); or s.Trim(), it doesn't modify the original string, instead it returns a new string.

So for your case something like:

string newstr = s.Trim();
//OR
string newstr = s.Remove(0,1); 

should work.

But remember s.Trim() would remove any kind of white space from beginning or end of string. If that is your desired behaviour use that.

Similarly you can use string.Replace but that will replace all occurrence of new line character from the string.

And your s.Remove(0,1) will remove the first character irrespective of whether it is a new line character or not.

Give this a shot:

string s = "\n1234";

s = s.Replace("\n", string.Empty);

You can use:

string s = "\n1234".TrimStart(new char[]{'\n'}); // search for \n at the start of the string

or

string s = "\n1234".TrimEnd(new char[]{'\n'});// search for \n at the end of the string

or

string s = "\n1234".Trim(new char[]{'\n'});// search for \n at the start and the end of the string
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top