HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Replacing from a list chars in a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
charsreplacinglistfromstring

Problem

Often I need to clean a file name using Path.GetInvalidFileNameChars(), however I do not know of a way to search for any of the invalid letters (except by using Regex) in one pass.

public string LoopMethod()
{
    StringBuilder sb = new StringBuilder(fileName);
    foreach(var invalidChar in Path.GetInvalidFileNameChars())
    {
        sb.Replace(invalidChar, '_');
    }
    return sb.ToString();
}

Regex invalidCharsRegex;
public void RegexMethodInit()
{
    var invalidChars = Path.GetInvalidPathChars().Select(c => Regex.Escape(c.ToString())).ToString();
    invalidCharsRegex = new Regex(string.Join("|", invalidChars));
}

public string RegexMethod(string fileName)
{
    return invalidCharsRegex.Replace(fileName, "_");
}


Is one of those ways the "correct" way to to this or is there a better function I am missing?

Solution

foreach(var c in Path.GetInvalidPathChars())
    path = path.replace(c, '_')


That's a bit inefficient as it can allocate a string on every itteration, but usually not a problem. Alternative:

var chars = Path.GetInvalidPathChars()
path = new string(path.Select(c => chars.Contains(c) ? '_' : c).ToArray())

Code Snippets

foreach(var c in Path.GetInvalidPathChars())
    path = path.replace(c, '_')
var chars = Path.GetInvalidPathChars()
path = new string(path.Select(c => chars.Contains(c) ? '_' : c).ToArray())

Context

StackExchange Code Review Q#22986, answer score: 4

Revisions (0)

No revisions yet.