Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .Trim not working for some reason

Tags:

c#

.net

Alright, so basically, I'm trimming a string then making it lowercase. The lowercase part works perfectly well, but the sentence doesn't get trimmed. Any clue?

var result12 = TrimTheSentence("   John.   Doe@ gmaiL . cOm");

//the method is

    public static string TrimTheSentence(string givenString)
    {
        givenString = givenString.Trim();
        return givenString.ToLower();
like image 378
user2629770 Avatar asked Jul 29 '13 09:07

user2629770


2 Answers

This is what you are looking for, you could shorten your method to just one line:

return givenString.Replace(" ", "").ToLower();

Trim() removes blank spaces from front and end of the string. It will not remove spaces that are in the string.

Examples:

"  Test String".Trim(); //Output: "Test String", it will remove only the leading spaces, but not the space between Test and String.
" Test String   ".Trim(); //Output: "Test String", it will remove leading and trailing spaces.

MSDN link: http://msdn.microsoft.com/en-us/library/system.string.trim.aspx

like image 61
unlimit Avatar answered Sep 28 '22 08:09

unlimit


Trim removes spaces from the start/end, not from the entire string. Try:

return givenString.Replace(" ", "");
like image 30
Richard Szalay Avatar answered Sep 28 '22 10:09

Richard Szalay