首页 > 解决方案 > 使用 C#,Strting.Trim() 没有删除我的网络刮板中的前导和尾随空格

问题描述

不知道我做错了什么,有问题的字符串是:

  Type    Family,   Strategy       

我将它存储在一个名为 item 的变量中,然后调用 item.Trim() 但是输出没有改变。这是我的整个功能的代码:

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;
    }

我的目标是仅当第一个单词与“feature”匹配时才将“item”添加到我的数组中。关于“featureLength”的部分只是为了获取第一个单词,这不起作用,因为我的字符串在调用 item.Trim() 后仍然有前导空格。

在上面的示例中,我传递了上面指出的项目,“feature”是“Type”,“found”是 false。

标签: c#stringtrim

解决方案


这是您当前的呼叫Trim

item.Trim();

Trim方法不会更改您正在调用的字符串的内容。它不能 - 字符串是不可变的。相反,它返回对应用了修剪的字符串的引用。所以你要:

item = item.Trim();

请注意,您仍然需要额外的字符串操作才能正确处理 ,但这至少会根据需要修剪字符串开头和结尾的空格。


推荐阅读