C # - efficiently finding and replacing a char array in a string

I have for example

string str ='Γ€pple'; string strNew=""; char[] A = {'Γ€','Á','Γ‚','Γ„'}; char[] a = {'Γ ','Γ‘','Γ’','Γ€'}; 

I want to browse the page and see if it finds a replacement for the Ascii 'A' code. Thus, 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 comparison function does not work, so what other function can I use?

+4
source share
3 answers

Looks like you could just use:

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

but there are, of course, more effective ways to do this. In particular, avoid string concatenation in a loop.

I assume that there are approaches to Unicode normalization that do not require hard coding of all this data. I am sure that somewhere I remember where there are backup copies of the encoding, but I can’t put it on it ... EDIT: I suspect it's near String.Normalize - it's worth a look, at least.

At least that 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); 
+5
source

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]; } 
+2
source

Try with regex (first replace with "A" and then with "a":

 string result = Regex.Replace("Γ€pple", "([ÀÁÂÄ])", "A", RegexOptions.None); 

And then you can do the same for "a".

0
source

All Articles