Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing all the '\' chars to '/' with C#

Tags:

string

c#

replace

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".

like image 938
prosseek Avatar asked May 17 '11 16:05

prosseek


People also ask

How do you replace all occurrences of a character in a string in C?

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.

How do you replace all characters?

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.

What is the '\ of character in C?

\0 is zero character. In C it is mostly used to indicate the termination of a character string.

How do I replace multiple characters in a string in C++?

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.


2 Answers

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.

like image 98
Darin Dimitrov Avatar answered Sep 22 '22 18:09

Darin Dimitrov


string first = @"c:/abc/def";
string sec = first.Replace("/","\\");
like image 41
kmerkle Avatar answered Sep 25 '22 18:09

kmerkle