Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove spaces and newlines in a string [duplicate]

Tags:

sorry if they are not very practical for C # Asp.Net, I hope to make me understand I have this situation

string content = ClearHTMLTags(HttpUtility.HtmlDecode(e.Body));
content=content.Replace("\r\n", "");
content=content.Trim();
((Post)sender).Description = content + "...";            

I would make sure that the string does not contain content nor spaces (Trim) and neither carriage return with line feed, I'm using the above code inserted but it does not work great either

any suggestions??

Thank you very much Fabry

like image 816
fabry19dice Avatar asked Jan 09 '14 10:01

fabry19dice


People also ask

How do I remove double spacing from a string?

Using regexes with "\s" and doing simple string. split()'s will also remove other whitespace - like newlines, carriage returns, tabs.

How do I remove spaces between words in a string?

In Java, we can use regex \\s+ to match whitespace characters, and replaceAll("\\s+", " ") to replace them with a single space.

How do you remove spaces before and after a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.

How do I remove spaces from a char string?

Use replace () function to replace all the space characters with a blank. The resulting string will not have any spaces in-between them.


2 Answers

You can remove all whitespaces with this regex

content = Regex.Replace(content, @"\s+", string.Empty);

what are whitespace characters from MSDN.

Btw you are mistaking Trim with removing spaces, in fact it's only removing spaces at the begining and at the end of string. If you want to replace all spaces and carige returns use my regex.

like image 103
Kamil Budziewski Avatar answered Sep 30 '22 02:09

Kamil Budziewski


this should do it

String text = @"hdjhsjhsdcj/sjksdc\t\r\n asdf";

        string[] charactersToReplace = new string[] { @"\t", @"\n", @"\r", " " };
        foreach (string s in charactersToReplace)
        {
            text = text.Replace(s, "");
        }
like image 24
Ehsan Avatar answered Sep 30 '22 01:09

Ehsan