Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove space in the middle using c# [duplicate]

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.

like image 554
Kalaivani Avatar asked Mar 30 '12 11:03

Kalaivani


3 Answers

Write like below

name = name.Replace(" ","");
like image 119
Sai Kalyan Kumar Akshinthala Avatar answered Oct 01 '22 07:10

Sai Kalyan Kumar Akshinthala


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));
    }
}
like image 33
Sunil Chavan Avatar answered Oct 01 '22 06:10

Sunil Chavan


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>()
    )
like image 39
CSharpCoder Avatar answered Oct 01 '22 08:10

CSharpCoder