Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Efficient search and replace char array in string

Tags:

c#

asp.net

I have e.g.

string str ='Àpple';
string strNew="";
char[] A = {'À','Á','Â','Ä'};
char[] a = {'à','á','â','ä'};

I want to look through the str and see if found replace with Ascii code 'A' . So the result should be:

strNew = 'Apple';

Here is my code:

for (int i = 0; i < str.Length; i++)
{ 
    if(str[i].CompareTo(A))
       strNew += 'A'
    else if(str[i].CompareTo(a)) 
       strNew +='a'
    else
       strNew += str[i];
}

But the compare function doesn't work, so what other function I can use?

like image 817
Benk Avatar asked Jun 19 '12 17:06

Benk


2 Answers

It sounds like you could just use:

if (A.Contains(str[i]))

but there are certainly more efficient ways of doing this. In particular, avoid string concatenation in a loop.

My guess is that there are Unicode normalization approaches which don't require you to hard-code all this data, too. I'm sure I remember one somewhere, around encoding fallbacks, but I can't put my finger on it... EDIT: I suspect it's around String.Normalize - worth a look, at least.

At the very least, this would be more efficient:

char[] mutated = new char[str.Length];
for (int i = 0; i < str.Length; i++)
{
    // You could use a local variable to avoid calling the indexer three
    // times if you really want...
    mutated[i] = A.Contains(str[i]) ? 'A'
               : a.Contains(str[i]) ? 'a'
               : str[i];
}
string strNew = new string(mutated);
like image 87
Jon Skeet Avatar answered Nov 03 '22 11:11

Jon Skeet


This should work:

for (int i = 0; i < str.Length; i++)
{ 
    if(A.Contains(str[i]))
        strNew += 'A'
    else if(a.Contains(str[i])) 
          strNew +='a'
    else
        strNew += str[i];
}
like image 39
Samy Arous Avatar answered Nov 03 '22 09:11

Samy Arous