9

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.

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
Kalaivani
  • 477
  • 3
  • 9
  • 17

3 Answers3

45

Write like below

name = name.Replace(" ","");
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>()
    )