Search code examples
c#stringtrim

Strting.Trim() is not removing leading and trailing spaces in in my web scraper, using C#


Not sure what I'm doing wrong, the string in question is:

  Type    Family,   Strategy       

I store this in a variable called item, and call item.Trim() however the output is unchanged. Here is the code for my whole function:

private bool checkFeatureList(string item, string feature, bool found)
    {

        //Only match if the feature is the first word TO DO
        if (item.Contains(feature) && found == false)
        {
            int featureLength = feature.Length - 1;
            item.Trim();
            if (item.Substring(0, featureLength) == feature)
            {
                //Have not found the type yet, so add it to the array
                found = true; //Only need the first match
                //feature = item; //Split on double space TO DO
                cleanFeatureList.Add(item);
            }
        }

        return found;
    }

My goal is to add "item" to my array only if the first word matches "feature". The bit about "featureLength" is only to get the first word, this isn't working because my string still has leading spaces after calling item.Trim().

In the example above, I am passing in item as I indicated above, "feature" is "Type" and "found" is false.


Solution

  • This is your current call to Trim:

    item.Trim();
    

    The Trim method doesn't change the content of the string you're calling on. It can't - strings are immutable. Instead, it returns a reference to a new string with the trimming applied. So you want:

    item = item.Trim();
    

    Note that you'll still need additional string manipulation to handle   appropriately, but this will at least trim whitespace from the start and end of the string as you want.