Remove space from a path

649 views Asked by At

I have a string with a path that looks like this:

"Salle de bains / 01-Points d'eau / 01-01 Vasques"

Now I want to change this path to look like this:

"Salle de bains/01-Points d'eau/01-01 Vasques"

I already tried Trim, Replace, and Substring without success. I then tried this method:

private string UrlCreator(string dir)
{
    string dirFinish = dir;

    foreach(Char item in dirFinish)
    {
        if (Char.IsWhiteSpace(item) && ((item-1).Equals('/') || (item+1).Equals('/')))
        {
            string charToChange = item.ToString();
            charToChange = "";
        }
        else { }
    }

    return dirFinish;
}

But this doesn't give me the desired result. How can I achieve this?

3

There are 3 answers

0
Michael Hancock On BEST ANSWER

Using the string replace method:

var myString = "Salle de bains / 01-Points d'eau / 01-01 Vasques";
var result = myString.Replace(" / ", "/");

// result -> "Salle de bains/01-Points d'eau/01-01 Vasques"
2
Cid On

Another way to achieve that is combining Split(" / ") along with string.Join("/"); :

var input = "Salle de bains / 01-Points d'eau / 01-01 Vasques"; 
var output = string.Join("/", input.Split(" / ")); // Salle de bains/01-Points d'eau/ 01-01 Vasques

Performances are quite the same than using Replace(), however, Replace() is certainly easier to read and Michael Hancock's answer is the way to go


You can use RegEx too if you don't know the number of spaces before and after the / :

var input = "Maison 42 / Salle de bains /01-Points d'eau/ 01-01 Vasques";

string pattern = @"\s*/\s*";
string replacement = "/";
// using System.Text.RegularExpressions;
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

Output is

Maison 42/Salle de bains/01-Points d'eau/01-01 Vasques

The pattern \s*/\s* does the following :

\s* searches for any number of white spaces

/ followed by a forward slash

\s* followed by any number of white spaces

0
Dmitry Bychenko On

Generalization: if you want to remove arbitrary number of white spaces before and after / you can use regular expressions:

using System.Text.RegularExpressions;

...

// two spaces after 1st '/'; no spaces before 2nd '/' 
string source = "Salle de bains /  01-Points d'eau/ 01-01 Vasques";
string result = Regex.Replace(source, @"\s*/\s*", "/"); 

Console.Write(result);

Outcome:

Salle de bains/01-Points d'eau/01-01 Vasques

Another possibility is Linq

using System.Linq;

...

string result = string.Join("/", source.Split('/').Select(item => item.Trim()));