Reputation: 847
I am using C# to remove a special character from a string:
while (str.Contains("@"))
str = str.Remove(str.IndexOf("@"), 1);
but this produce an error:
StartIndex can not be less than zero.
The str
variable really contains @
character but the result value of IndexOf() method is -1.
I guess that is because the string encoding is utf-8, but I don't know how to manipulate the string.
The value of str
is NfyCAlcvxu1Xqw@ًں‘„ًں
.
Upvotes: 0
Views: 4564
Reputation: 9365
From MSDN of string.Contains
This method performs an ordinal (case-sensitive and culture-insensitive) comparison. The search begins at the first character position of this string and continues through the last character position.
So you have to use ordinal comparison also in the IndexOf
:
while (str.Contains("@"))
str = str.Remove(str.IndexOf("@",StringComparison.Ordinal), 1);
Upvotes: 9
Reputation: 808
That bit of code that you provided alone, seems to be fine.
However, I would suggest a different approach to the problem:
C#
str = str.Replace("@", "");
Upvotes: 1