How to remove space

Got a fixed part, always skip this, thanks everyone

Hello everybody,

String test = "John, Jane";

test.Replace(" ","");

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

How would you delete just space in a row or any potentially potential space?

Why is there 3 elements in the array, not 2?

+3
source share
5 answers

To remove any space, simply replace it with any empty string:

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

Note that simply calling string.Replacewill not do this - the strings are immutable, so the return value string.Replaceis a link to a new string with appropriate replacements.

+13
source

It's simple:

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

If you need to remove spaces, you will need regex :

using System.Text.RegularExpressions;
Regex r=new Regex("\\s+");
test=r.Replace(test,"");

Re: Why is there 3 elements in the array, not 2?

, (split arg 1 + 2), , John Jane:

["John", "", "Jane"] // (in JSON notation ;))
+5
        string test2 = test.Replace(" ", "");
+4

, string noWhiteSpace = Regex.Replace("John, Jane", @"\s", string.Empty); , string noSpace = "John, Jane".Replace(" ",string.Empty);

, :

, , . , , .

, :

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

, , .

+1

, :

String test = "John, Jane";

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

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

3 , 2?

For two reasons: 1) when you call Replace, you generate a new string , and you need to save it in some variable - the original string is unchanged. 2) Then you used space ( ' ') as one of the delimiters in the call Split; you don’t need it (you remove all spaces in the previous line).

0
source

Source: https://habr.com/ru/post/1787792/


All Articles