How can I replace all the '\' chars in a string into '/' with C#? For example, I need to make @"c:/abc/def" from @"c:\abc\def".
Using Function The main() function calls the replacechar(char *s, char c1, char c2) function to replace all occurrences of the character with another character.
Summary. To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.
\0 is zero character. In C it is mostly used to indicate the termination of a character string.
Using std::replace function The recommended solution is to use the standard algorithm std::replace from the <algorithm> header. It does one linear scan of the string and in-place replaces all the matching characters.
The Replace function seems suitable:
string input = @"c:\abc\def";
string result = input.Replace(@"\", "/");
And be careful with a common gotcha:
Due to string immutability in .NET this function doesn't modify the string instance you are invoking it on => it returns the result.
string first = @"c:/abc/def";
string sec = first.Replace("/","\\");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With