You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C#的String.Remove()方法移除非字母数字字符时存在遗漏,求排查

问题原因

你的代码问题出在遍历字符串时移除字符后没有调整索引。当调用thestr.Remove(i, 1)后,字符串长度减1,原本位于i+1位置的字符会前移到i的位置,但循环变量i仍在递增,直接跳过了这个新移到i位置的字符。比如原字符串里逗号后的空格,在移除逗号后,空格移到了i=5的位置,但i马上变成6,根本没检查这个空格,所以它被保留了下来。

修复方案

方案1:调整循环索引

移除字符后让i减1,确保下一次循环能检查到前移过来的字符:

string thestr = "Hello, my name is Adam";
thestr = thestr.ToLower();
for (int i = 0; i < thestr.Length; i++)
{
    if (Char.IsPunctuation(thestr, i) || Char.IsWhiteSpace(thestr, i))
    {
        thestr = thestr.Remove(i, 1);
        i--; // 移除后回退索引,避免跳过字符
    }
}
Console.WriteLine(thestr);

方案2:倒序遍历(更稳妥)

从字符串末尾往前遍历,移除字符不会影响前面未遍历的索引,无需调整i:

string thestr = "Hello, my name is Adam";
thestr = thestr.ToLower();
for (int i = thestr.Length - 1; i >= 0; i--)
{
    if (Char.IsPunctuation(thestr, i) || Char.IsWhiteSpace(thestr, i))
    {
        thestr = thestr.Remove(i, 1);
    }
}
Console.WriteLine(thestr);

方案3:用LINQ简化代码(高效简洁)

直接筛选出字母数字字符拼接成新字符串,避免频繁修改原字符串的性能开销:

using System.Linq;

string thestr = "Hello, my name is Adam";
string result = new string(thestr.ToLower().Where(c => Char.IsLetterOrDigit(c)).ToArray());
Console.WriteLine(result);

方案4:正则表达式替换

用正则匹配所有非字母数字字符并替换为空:

using System.Text.RegularExpressions;

string thestr = "Hello, my name is Adam";
string result = Regex.Replace(thestr.ToLower(), @"[^a-z0-9]", "");
Console.WriteLine(result);

内容的提问来源于stack exchange,提问作者user26616360

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 02:54:53