Alireza Zojaji
Alireza Zojaji

Reputation: 847

C# string.IndexOf method doesn't work

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

Answers (2)

Ofir Winegarten
Ofir Winegarten

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

DesertFox
DesertFox

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

Related Questions