Reputation: 4733
I have a string name which has -
as a special character which has to be replaced by \-
.
name = name .Contains('-') ? name .Replace('-', '\-') : name;
The replace method throws error of unrecognized escape sequence.
When i try to do this
name = name .Contains('-') ? name .Replace('-', '\\-') : name;
too many characters in character literal.
Some example of name is :
abc-123-45g
xyz-1-2-3
ref-124
What is the best way to replace the character?
Upvotes: 1
Views: 439
Reputation: 9365
Well \-
is not a character. its a string.
So you should use the overload the takes strings not characters:
name = name.Contains('-') ? name.Replace("-", "\\-") : name;
Also you don't really need that Contains
condition. So you end up with:
name = name.Replace("-", "\\-");
Upvotes: 1