This is code from the book - "Programming Interviews Exposed" 2nd Edition - Pages 78 & 79 - Remove Specified Characters Exercise (continued below)
void Main()
{
string se = "I_am_the_string_to_modify";
string re = "amthe";
Console.WriteLine(se);
Console.WriteLine(re);
char[] s=se.ToCharArray();
char[] r=re.ToCharArray();
bool[] flags=new bool[128];
int len=s.Length;
int src,dst;
for(src=0;src<len;++src)
{
Console.Write(r[src]+",");
flags[r[src]]=true;
}
src=0;
dst=0;
while(src<len)
{
if(!flags[(int)s[src]])
{
s[dst++]=s[src];
}
++src;
}
string str=new string(s,0,dst);
Console.WriteLine(str);
}
If I try to run this I get IndexOutOfRangeException: Index was outside the bounds of the array. due to line 18. The author is trying to do the same kind of thing on line 26.
The point is to create a look-up array that identifies the chars that are to be removed. I have a working version of this but I did not use the nested array indexes.
Is there a way that this should be working? I don't see how the nested arrays would ever work.
This is not a C# program. It's C source code with extension .cs.
In the 80's and early 90's, when we, C programmers, learned C++, we all did this: Think C and transpose to C++. That was the worst way to learn C++. Doing it with C# is even worse. When programming in C#, never think C.
FWIW, here's the LINQ solution to your problem in .NET 4:
Console.WriteLine(string.Concat(se.Where(ch => re.IndexOf(ch) < 0)));
Here's a Regex-based solution (arguably less good because it may fail with some special chars in re):
Console.WriteLine(new Regex("["+re+"]").Replace(se, ""));
Your problem is that you're indexing into r (a 5-element array) but looping to s.Length (25).
Change line 12 to int len=r.Length; and line 20 to len=s.Length;.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With