Tuesday, July 14, 2009

Can any one of you solve this programm in C++, if P & T are strings with lengths R & S repectively?

And are stored as arrays with one charecter per element , find the indedx(location) of P in T??

Can any one of you solve this programm in C++, if P %26amp; T are strings with lengths R %26amp; S repectively?
Basically you have a couple of indexes





index_in_P


index_in_T





They both start at the beginning. You use a main for loop to walk through T.





if P[index_in_P] == T[index_in_T]


start seeing if the string matches all the way


for the rest of the letters in P (up to length R)


if P[index_in_P] == T[index_in_T+index_in_P]


you are still matching, good, increment index_in_P


else


they no longer match





index_in_T only increments when you are looking for a new start letter, it is the index you will return. If it is possible P is not in T, you need to make sure you don't go out of bounds in T.
Reply:Heres the C way:





int i, j;


for (i = 0; i %26lt; S - R; ++i)


{


for (j = 0; j %26lt; R; ++j)


{


if (P[j] != T[i+j])


break;


}


if (j == R) // got to the end of the loop successfully


break;


}


if (i == S - R) // got to the end without finding P in T


printf( "not found\n" );


else


printf( "found at %d\n", i );





In C++, I would use the string.find function:





size_type pos = T.find( S );


if (pos == npos) // npos is a constant


cout %26lt;%26lt; "not found" %26lt;%26lt; endl;


else


cout %26lt;%26lt; "found at " %26lt;%26lt; pos %26lt;%26lt; endl;





The more verbose way would be to use string.substr:





int pos;


for (pos = 0; pos %26lt; S - R; ++pos)


{


if (T.substr( pos, R ) == P)


break; // found it


}


if (pos == S - R)


cout %26lt;%26lt; "not found" %26lt;%26lt; endl;


else


cout %26lt;%26lt; "found at " %26lt;%26lt; pos %26lt;%26lt; endl;





And the most generic way using a C++ algorithm template:





char * pos = search( T, T+S, P, P+R );


if (pos == T+S)


cout %26lt;%26lt; "not found" %26lt;%26lt; endl;


else


cout %26lt;%26lt; "found at " %26lt;%26lt; (int)( pos - T ) %26lt;%26lt; endl;


No comments:

Post a Comment