c# - 使用 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。
解决方案
这是您当前的呼叫Trim
:
item.Trim();
该Trim
方法不会更改您正在调用的字符串的内容。它不能 - 字符串是不可变的。相反,它返回对应用了修剪的新字符串的引用。所以你要:
item = item.Trim();
请注意,您仍然需要额外的字符串操作才能正确处理
,但这至少会根据需要修剪字符串开头和结尾的空格。
推荐阅读
- javascript - Webpack Encore - 模块规则 - 将 scss 变量导出/导入到 javascript 时出错
- javascript - 将表格单元格链接到复选框 Javascript
- python - Python模板forloop不工作不止一次
- mysql - 将列数据转换为列名
- python - YAML/JSON 必需属性不适用于对象属性
- angular - Angular + webpack + require.context:避免在主包中包含模拟数据
- web-scraping - Python 请求 - 无法获得 POST 表单响应(仅返回表单)
- node.js - 无法使用适用于 Node.js 的 Admin SDK 在 Firebase 存储中将 Content-Disposition 覆盖为“内联”
- php - 未使用 mysqli_real_escape_string() 在表单提交方法中获取数组值
- c# - HttpRootDirectory 的嵌入式资源文件夹路径