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

3

10

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.

Christhood answered 30/3, 2012 at 11:19 Comment(0)
F
47

Write like below

name = name.Replace(" ","");
Fax answered 30/3, 2012 at 11:20 Comment(1)
How about name = name.Replace(" ", string.Empty); ? Same meaning, but more conventional :)Moorman
S
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));
    }
}
Slipon answered 30/3, 2012 at 11:29 Comment(0)
P
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>()
    )
Punner answered 24/7, 2017 at 12:18 Comment(1)
Avoid code only answersCorell

© 2022 - 2024 — McMap. All rights reserved.