how to remove space in the middle using c#? I have the string name="My Test String"
and I need the output of the string as "MyTestString"
using c#.
Please help me.
Asked
Active
Viewed 3.9k times
9

Neil Knight
- 47,437
- 25
- 129
- 188

Kalaivani
- 477
- 3
- 9
- 17
3 Answers
45
Write like below
name = name.Replace(" ","");

Sai Kalyan Kumar Akshinthala
- 11,704
- 8
- 43
- 67
-
2How about name = name.Replace(" ", string.Empty); ? Same meaning, but more conventional :) – Jviaches Oct 30 '18 at 16:40
9
using System;
using System.Text.RegularExpressions;
class TestProgram
{
static string RemoveSpaces(string value)
{
return Regex.Replace(value, @"\s+", " ");
}
static void Main()
{
string value = "Sunil Tanaji Chavan";
Console.WriteLine(RemoveSpaces(value));
value = "Sunil Tanaji\r\nChavan";
Console.WriteLine(RemoveSpaces(value));
}
}

Sunil Chavan
- 524
- 5
- 15
3
Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.
new string
(stringToRemoveWhiteSpaces
.Where
(
c => !char.IsWhiteSpace(c)
)
.ToArray<char>()
)

CSharpCoder
- 61
- 3