Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何删除C#字符串中的空格?_C# - Fatal编程技术网

如何删除C#字符串中的空格?

如何删除C#字符串中的空格?,c#,C#,我有以下代码: String test = "John, Jane"; test.Replace(" ",""); String[] toList = test.Split(',', ' ', ';'); 如何删除字符串中的空格或任何可能显示的空格 为什么数组中有3项而不是2项?要删除任何空格,只需将其替换为任何空字符串: test = test.Replace(" ", ""); 请注意,仅调用string.Replace是不行的-字符串是不可变的,因此string.Replace的返

我有以下代码:

String test = "John, Jane";

test.Replace(" ","");

String[] toList = test.Split(',', ' ', ';');
如何删除字符串中的空格或任何可能显示的空格


为什么数组中有3项而不是2项?

要删除任何空格,只需将其替换为任何空字符串:

test = test.Replace(" ", "");
请注意,仅调用
string.Replace
是不行的-字符串是不可变的,因此
string.Replace
的返回值是对具有相关替换项的新字符串的引用。

简单如下:

        string test2 = test.Replace(" ", "");
test=test.Replace(" ","");
如果要删除任何空白,则需要:

Re:为什么数组中有3项而不是2项

因为您同时使用逗号和空格进行拆分(拆分arg 1+2),因为在
John
Jane
之间同时使用逗号和空格,您得到:

["John", "", "Jane"] // (in JSON notation ;))

如果要删除所有类型的空白,可以使用
string noWhiteSpace=Regex.Replace(“John,Jane”,“@”\s”,string.Empty)
如果只想删除空格字符,请使用
string noSpace=“John,Jane”.Replace(“,string.Empty”)

刚才看到了您在编辑中添加的问题的第二部分:

数组中有三项,因为测试字符串将在要拆分的字符列表中包含的每个标记处拆分。字符串同时包含空格和逗号,在逗号处拆分,在空格处拆分

如果不需要空条目,可以使用以下选项:

String[] toList = test.Split(new char[] {',', ' ', ';'}, StringSplitOptions.RemoveEmptyEntries);

当然,如果删除了空格,那么就没有任何空格可以拆分。

因此完整的解决方案是:

String test = "John, Jane";

test = test.Replace(" ","");

String[] toList = test.Split(',', ';');
为什么数组中有3项而不是2项


有两个原因:1)当您调用
Replace
时,您正在生成一个新的字符串,您需要将其存储在某个变量中-原始字符串是不可变的。2) 然后,在调用
拆分
时,您使用了一个空格(
'
)作为分隔符之一;你不需要它(你正在删除前一行中的所有空格)。

@rod:鉴于问题中显示的代码中存在错误,你还需要任何帮助吗?
String test = "John, Jane";

test = test.Replace(" ","");

String[] toList = test.Split(',', ';');