To remove spaces from a string with C#, use the Replace function, passing in the value you want to remove and the value you want to replace it with. To remove characters, make the second parameter an empty string.
You can replace a single character or a sequence of characters.
Here’s code to demonstrate the Replace function on a string variable.
Notice on line 6 that calling the Replace on the string does not change the string. You need to use the technique on line 9 where we put the modified value back into the “test” variable.
void Main() { string test = "asd 123 qwe 789"; Console.WriteLine($"'{test}' - {test.Length} characters"); test.Replace(" ", ""); Console.WriteLine($"'{test}' - {test.Length} characters"); test = test.Replace(" ", ""); Console.WriteLine($"'{test}' - {test.Length} characters"); }
Here are the results when running the code
‘asd 123 qwe 789’ – 24 characters
‘asd 123 qwe 789’ – 24 characters
‘asd123qwe789’ – 12 characters