C#网页爬虫中String.Trim()无法去除首尾空格问题求助
解决String.Trim()无法去除首尾空格的问题
我来帮你定位问题并解决它,你的代码里有两个关键问题导致Trim()没生效:
1. C#字符串是不可变类型,Trim()不会修改原变量
String.Trim()方法不会改变原字符串的内容,它会返回一个去除了首尾空白的新字符串。你现在只是调用了item.Trim();但没有把返回值重新赋值给item,所以原变量的内容完全没变化。
正确的写法应该是:
item = item.Trim();
2. 你的字符串里包含的是非断行空格( ),默认Trim()不处理它
你提到的字符串Type Family, Strategy里的 对应的是Unicode字符U+00A0(非-breaking空格),而C#默认的Trim()方法只会去除普通空格(U+0020)、制表符、换行符这些常规空白字符,不会处理U+00A0。
要解决这个问题,你可以用两种方法:
- 方法一:指定要去除的字符集合
同时覆盖普通空格和非断行空格:item = item.Trim(new char[] { ' ', '\u00A0' }); - 方法二:覆盖所有空白字符
如果你不确定还有其他特殊空白,可以用char.IsWhiteSpace来过滤所有首尾空白:item = new string(item.TrimStart(char.IsWhiteSpace).TrimEnd(char.IsWhiteSpace).ToArray());
修改后的完整函数代码
结合上面的修复点,我还调整了你判断第一个单词的逻辑(原来的featureLength = feature.Length - 1是错误的,会少取一个字符),同时加了索引越界的防护:
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) { // 修复:处理不可变字符串 + 去除包括非断行空格在内的空白 item = item.Trim(new char[] { ' ', '\u00A0' }); // 修复featureLength的错误:直接使用feature的完整长度 int featureLength = feature.Length; // 先判断长度,避免索引越界异常 if (item.Length >= featureLength && item.Substring(0, featureLength) == feature) { //Have not found the type yet, so add it to the array found = true; //Only need the first match cleanFeatureList.Add(item); } } return found; }
针对你的测试场景验证
当传入item = "Type Family, Strategy",feature = "Type"时:
- 执行Trim后,item会变成
"Type Family, Strategy"(首尾的非断行空格被去除) item.Substring(0, 4)会得到"Type",和feature完全匹配,因此会把item加入cleanFeatureList,同时found设为true。
内容的提问来源于stack exchange,提问作者user9544908




