1

I want to replace any space between in word in with dash in C#. But my problem is when I want remove space in sample string like this:

"a  b"

or

"a    b"

When I try this, I get this result:

"a--b" and "a---b"

How can I put one dash for any count of space between the word?

Like this:

"a b"

"a-b"

Black Frog
  • 11,595
  • 1
  • 35
  • 66
SH.Developer
  • 167
  • 2
  • 3
  • 16

4 Answers4

3

you can use like below

string xyz = "1   2   3   4   5";
xyz = string.Join( "-", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));

Reference

  1. How do I replace multiple spaces with a single space in C#?
  2. How to replace multiple white spaces with one white space
Community
  • 1
  • 1
शेखर
  • 17,412
  • 13
  • 61
  • 117
2

You can simply use Regex.Replace here.

Regex.Replace("a    b", @"\s+", "-");

\s looks for a space and + counts for spaces, if one or more spaces found sequentially. The pattern will be matched and replaced.

Shaharyar
  • 12,254
  • 4
  • 46
  • 66
2

This can be done with many approaches. using Regular Expressions:

    string a = "a         b   c de";
    string b = Regex.Replace(a, "\\s+", "-");             

Or if you dont want to use Regex, Here's a function which will take a string and the character to replace as arguments and return the formatted string.

    public string ReplaceWhitespaceWithChar(string input,char ch)
    {
        string temp = string.Empty;
        for (int i = 0; i < input.Length; i++)
        {

            if (input[i] != ' ')
            {
                temp += input[i];
            }
            else if (input[i] == ' ' && input[i + 1] != ' ')
            {
                temp += ch;
            }
        }
        return temp;
    }        
0

You can use this code for your requirement

        string tags = "This           sample";
        string cleanedString = System.Text.RegularExpressions.Regex.Replace(tags, @"\s+", "-");

        Response.Write(cleanedString);

And result will be :

"This-sample"

I hope it will work for you.

Neeraj Purohit
  • 243
  • 3
  • 23