What is the correct way to do an Replace in a string-like variable?

Asked

Viewed 156 times

5

I need to create a folder on the file server and realized that the variable that receives one of the information is coming with invalid characters ( / : * ? " < > |) for creating a folder on Windows.

string Caminho = Path.Combine(PastaPadrao,txtInfoUser.Text);

In the case of character (:), it is relevant to the user and therefore needs to be recorded, but nothing prevents me from making a Replace() for underline, but painted the doubt: What is the correct way to do the Replace() in that case?

return Caminho.Replace(@"\", "_")
               .Replace(@"/", "_")
               .Replace(@":", "_")
               .Replace(@"*", "_")
               .Replace(@"?", "_")
               .Replace(@"""", "_")
               .Replace(@"<", "_")
               .Replace(@">", "_")
               .Replace(@"|", "_");

If I do it this way, 9 different instances of the string?

For now, I did it this way:

 StringBuilder CaminhoSemCaracteresInvalidos = new StringBuilder(Caminho);
CaminhoSemCaracteresInvalidos.Replace(@"\", "_")
                .Replace(@"/", "_")
                .Replace(@":", "_")
                .Replace(@"*", "_")
                .Replace(@"?", "_")
                .Replace(@"""", "_")
                .Replace(@"<", "_")
                .Replace(@">", "_")
                .Replace(@"|", "_");

return CaminhoSemCaracteresInvalidos.ToString();

My concern is to try to do the best way so that the application does not suffer at the end of the day, always trying to do what is right from the point of view of performance and good practice, but I also don’t know if I’m mounting an atomic bomb to kill a fly.

2 answers

2


If I do it this way, 9 different instances of the string?

That.

The second way seems more suitable because it does not make the allocations and allocation costs more expensive than people imagine*, if doing so in a loop with several paths can put enormous pressure on gargabe Collector and taking breaks.

The StringBuiler allows changing the string and the Replace() his is inplace, keeping only one allocation beyond the original and then another for the final result. I think the Caminho could be created in it, so already saving one more allocation.

But I wonder if it’s not worth making an algorithm that sweeps through string (standard or Builder, the latter is easier to do with performance) and create a new one by changing what you need in one step. I explain.

The second form still has the problem it will have 10 ties (the ToString() also has a) running across the text. You are not seeing but are running. So if you make a loop that handles all the characters you can give a much faster result. The other answer tried to do this but as it continued using Replace()created an exponential problem that is all a developer should avoid (only gives no apparent problem at low volume).

There’s a way to do it RegEx also, but in all the cases I’ve seen if do in the hand gets faster (I’ve seen people say that the RegEx may be faster, but never seen it happen when compared to manual code done correctly). I wouldn’t even think about it unless I’m a fanatic about this kind of solution (I think it’s unreadable after all, but it’s taste).

Total gain can be brutal.

Often the person does not care about it because he will use little, then years later this person, or someone who doesn’t even work on the team today, will use more intensely and will have something slow. Then nobody knows what it is, and they get desperate with the slowness and only look at the new code when the mistake is old.

But each one knows where the callus hurts, so you need to analyze if it’s worth the effort. For me it is always worth unless it is a lot of work and I know that the gain is really not necessary (rarely this happens for me).


*The allocation itself costs cheap, but putting pressure on the GC makes it go into action more often and longer, and worse, by switching generation other objects prematurely. It is not easy to notice this happening, it is something that goes slowly, it is more or less silent (some are very deaf and do not listen even when there is a small noise), so if you do a naive test it seems even fast.

  • 1

    This last paragraph of yours sums up my stance on the final outcome. Today with 10 users and 5 folders works well, but what about tomorrow when my application grows? She might not even grow up, stay with 10 users her whole life, but what? Take a chance? I still have a lot of beans and flour to eat, but the basics I feel I have to do...

2

I do it this way. I don’t know if it’s the right one, but it works.

public static string RemoveCharSpecials(string document)
    {
        var charsToRemove = new string[] { "@", ",", ".", ";", "'", "(", ")", "-", " ", "/" };

            if (!string.IsNullOrEmpty(document))
            {
                foreach (var c in charsToRemove)
                    document = document.Replace(c, string.Empty);
            }

            return document;
    }
  • 1

    "I don’t know if it’s the right one, but it works." ... So man, this is my concern... Working by working, I could do in N ways, but my goal is to seek to program in a way that does not blow the performance of my application. Sometimes it’s little attitudes that make all the difference.

  • When I used was made this fragment, it was with this concern. there was another q this locking the whole process and leaving more expensive. Regex broke all the way @Eduardooliveira

  • The idea is good, but it will probably be the worst solution because it creates a new string for each character found in what already exists, ie it will be common to have tens of Replace()s in almost all cases destroying the performance. It is right to build another string.

  • @Maniero by the most incredible q it seems had a gain, the string itself helped a lot. vc suggests which landing?

  • Prove that you won. but do the test under real conditions, using a test methodology that works, preferably https://benchmarkdotnet.org/. I say this because it doesn’t make sense to get faster by having a greater effort and the only explanation is that the test is done in a wrong way.

  • @Maniero is in Prod and there has been no more complaint. That is enough to prove q works. And your suggestion for improvement. one thing is the theory another the practice

  • 2

    Yes, I agree there was no complaint. https://answall.com/a/425183/101 Look at the photo I posted in my reply, the guy who’s wearing it doesn’t complain about anything, it’s good for him. You didn’t say it works, you said it got faster, you should have proof of it, in practice, because otherwise you’re theorizing about getting faster. If you can ask a question that is not a "do it for me that I want to see" that is not the purpose of the site, you can post that I will answer what is the practice, you already have the theory to help ask the question, so start making the code

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.