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.
Your problem is that you’re indexing into
r(a 5-element array) but looping tos.Length(25).Change line 12 to
int len=r.Length;and line 20 tolen=s.Length;.