My requirement
If string contains single slash (/ or \) it should be replace with double slash
Note :- string is randomly generated so, I have no control.
e.g. I have string
string str = @"*?i//y\^Pk@t9`n2";
When I tried as
str = str.Replace(@"\", @"\\").Replace(@"/",@"//");
it replaced // with //// but I need to replace only single slash(\) with double slash(\\).
Above code actual result is
*?i////y\^Pk@t9`n2
expected result is
*?i//y\\^Pk@t9`n2
Note :- If string contain double slash in sequence like "//" or "\\" then no need to modify string. but string contains single slash (/ or \) need to replace with double slash.
I have tried to find out other approach then I found following stack-overflow already question-answer
- Replace single backslash with double backslash
- Replace "\\" with "\" in a string in C#
- How to change backslash to double backslash?
Question :-
- How to check if string contain single slash and how to replace it?
- What best practice should follows while doing string manipulation like this?
Edit :-
I have random generated string comes from user like.
string str = @"*?i//y\^Pk@t9`n2";
sometimes that string contain single slash as above (\). if we consider above string without verbatim(@) it is not a valid string in C#. it gives compile time error. to make above string valid I need to replace "\" with "\\".
How I can achieve this?