patterncppMinor
Can this FindString function be optimized further, in terms of speed?
Viewed 0 times
thiscanfunctionoptimizedfurtherfindstringtermsspeed
Problem
int FindStr(char* str, int strsize, char* fstr, int from)
{
for(int i=from, j=0; i<strsize; i++)
{
if(str[i]==fstr[j])
j++;
else
{i-=j; j=0;}
if(fstr[j]=='\0')
return i-j+1;
}
return -1;
}The function searches for a string
fstr in str and returns its index in str if found, otherwise, it will return -1. It's also possible to specify where to start searching in the string.My question is, can I optimize this function further? Also, do you see any potential problems in this function?
Solution
Some comments to add to the first two of @200_success:
-
-
sizes are often passed as
-
modifying the loop variable within the loop is generally considered bad
practice
-
case
-
if
-
add some spaces around operators and after
-
strstr does a good job. Why reinvent?-
sizes are often passed as
size_t rather than int-
modifying the loop variable within the loop is generally considered bad
practice
-
i -= j executes on every loop unless there is a match. Mostly in thiscase
j is zero so the line has no effect, but it still executes-
if
fstr is an empty string it returns the wrong result (1)-
add some spaces around operators and after
if, forContext
StackExchange Code Review Q#38230, answer score: 4
Revisions (0)
No revisions yet.