C# Crawler
Sagiv Hadaya is crawling in C#...just for fun




 

Search & Replace insensitive

i have been asked, why c# implements in the string class a replace method that is so lame, why cant we replace a substring in a string no matter what the case is?

lame? i say, well, thats the fun, lets see how that will be implemented:

private int NoCaseReplace(ref string src, string find, string replace)

{

int x=0; /*counter*/

int occur=0; /*how many occurances*/

bool found = false; /*was the string found (in a single round)*/

int isrcl = src.Length;

int ifndl = find.Length;

find = find.ToLower();

/*converting to char array gives us the way to examine char by char*/

char[] str = src.ToCharArray();

char[] fnd = find.ToCharArray();

for (x=0;x<isrcl-1;x++)

{

if ((fnd[0]==str[x])||((fnd[0]-('a'-'A'))==str[x]))

{

int j=x;/*to prevent the global counter from being advanced*/

found = true;/*intialize to true*/

for (int y=0;y<ifndl;y++,j++)/*run in the find string and compare*/

{

if((fnd[y]!=str[j])&&((fnd[y]-('a'-'A'))!=str[j]))found = false;

}

}

if (found)

{

src = src.Remove (x,ifndl); /*remove the string we found*/

src = src.Insert (x,replace);/*insert the replace string*/

x+=ifndl-1; /*set the char array to point after the addition*/

found = false; /*reset to false*/

occur++;/*increase the number of occurance*/

}

}

return occur;

}

 

hope that all you who asked about this and my article about the ToCharArray usage, got a little more comfortable now.


Click here to visit the Radio UserLand website.
Click to see the XML version of this web page.
Click here to send an email to the editor of this weblog.
© Copyright 2002 Sagiv Hadaya.
Last update: 10/11/2002; 2:00:04 AM.