删除c#中的空格而不使用任何内置函数

0 c#

嗨,我是C#的初学者,我试图删除字符串中的空格.我使用以下代码:

public String RemoveSpace(string str1)
{

    char[] source = str1.ToCharArray();

    int oldIndex = 0;
    int newIndex = 0;
    while (oldIndex < source.Length)
    {
        if (source[oldIndex] != ' ' && source[oldIndex] != '\t')
        {
            source[newIndex] = source[oldIndex];
            newIndex++;
        }
        oldIndex++;
    }
    source[oldIndex] = '\0';
    return new String(source);

}
Run Code Online (Sandbox Code Playgroud)

但我现在面临的问题是,当我给 输入字符串"H E的L-" 的输出显示"赫尔L" 这是因为在最后一次迭代oldIndexarr[2]通过替换arr[4]最后一个字符"L"被冷落.有人可以指出正在做的错误吗?注意:不应使用正则表达式,修剪或替换功能.谢谢.

Ben*_*igt 6

一个String构造函数,允许您控制长度

所以只需将最后一行更改为

return new String(source, 0, newIndex);
Run Code Online (Sandbox Code Playgroud)

请注意,.NET不关心NUL字符(字符串可以很好地包含它们),因此您可以删除source[oldIndex] = '\0';它,因为它无效.