chamara
chamara

Reputation: 12709

Removing Trailing white spaces using TRIM()

i need to get items from a List with no leading or trailing white spaces.i'm trying the following code but still Trim() functions does't remove trailing spaces of the string.why does it happening?

  string ab = string.Empty;
            ab += "first" + ", ";//adding a white space to the string
            ab += "second" + ", ";
            ab += "third" + ", ";

            List<string> ls = ab.ToString().Split(',').ToList();//first, second, third,

            foreach (string item in ls)
            {
                item.Trim();//need to remove the space
                string a = item;//here still got the white space
            }

Upvotes: 1

Views: 6193

Answers (3)

Zed
Zed

Reputation: 595

foreach (string item in ls)
{
    string a = item.Trim();
}

If you split by ', ' instead of ',' you wouldn't need to Trim

Upvotes: 0

David Peden
David Peden

Reputation: 18434

String.Trim() returns the string that remains after all white-space characters are removed from the start and end of the current System.String object.

So you need to change the code inside your foreach loop to:

foreach (string item in ls) 
            { 
                string a = item.Trim();
            } 

Upvotes: 1

KodeKreachor
KodeKreachor

Reputation: 8882

Trim returns a string that is trimmed of whitespace characters at the beginning and the end, so you'll need to assign item.Trim() to a local variable, which will then be your trimmed string.

foreach (string item in ls)
{
    string trimmedItem = item.Trim(); //remove the space
    string a = trimmedItem;           //no white space here!
}

Upvotes: 2

Related Questions