Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 796 Vote(s) - 3.38 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to remove new line characters from a string?

#1
I have a string in the following format

string s = "This is a Test String.\n This is a next line.\t This is a tab.\n'

I want to remove all the occurrences of `\n` and `\r` from the string above.

I have tried `string s = s.Trim(new char[] {'\n', '\r'}); ` but it didn't help.
Reply

#2
If speed and low memory usage are important, do something like this:

var sb = new StringBuilder(s.Length);

foreach (char i in s)
if (i != '\n' && i != '\r' && i != '\t')
sb.Append(i);

s = sb.ToString();
Reply

#3
You want to use `String.Replace` to remove a character.

s = s.Replace("\n", String.Empty);
s = s.Replace("\r", String.Empty);
s = s.Replace("\t", String.Empty);

Note that `String.Trim(params char[] trimChars)` only removes leading and trailing characters in `trimChars` from the instance invoked on.

You could make an extension method, which avoids the performance problems of the above of making lots of temporary strings:

static string RemoveChars(this string s, params char[] removeChars) {
Contract.Requires<ArgumentNullException>(s != null);
Contract.Requires<ArgumentNullException>(removeChars != null);
var sb = new StringBuilder(s.Length);
foreach(char c in s) {
if(!removeChars.Contains©) {
sb.Append©;
}
}
return sb.ToString();
}
Reply

#4
I like to use regular expressions. In this case you could do:

string replacement = Regex.Replace(s, @"\t|\n|\r", "");



Regular expressions aren't as popular in the .NET world as they are in the dynamic languages, but they provide a lot of power to manipulate strings.
Reply

#5
FYI,

Trim() does that already.

The following LINQPad sample:

void Main()
{
var s = " \rsdsdsdsd\nsadasdasd\r\n ";
s.Length.Dump();
s.Trim().Length.Dump();
}

Outputs:

23
18




Reply

#6
I know this is an old post, however I thought I'd share the method I use to remove new line characters.

s.Replace(Environment.NewLine, "");


*References:*

[MSDN String.Replace Method][1] and [MSDN Environment.NewLine Property][2]

[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through