void find_substring(char * str_for_search_in, char * substring)
{
bool flag = false;
for (int i = 0; i < strlen(str_for_search_in) - strlen(substring); i++)
{
if (str_for_search_in.substr(i, strlen(substring)) == substring)
{
cout << i << " ";
flag = true;
break;
}
}
if (flag == false)
cout << "NONE";
}
I am converting my program from C++ strings to C strings and stuck on this issue in line 6
What's the issue here?
It was length.substring everywhere previously, i changed them to strlen() so they fit char *
I've tried changing data types somewhere but that didn't work
For starters the function in C should be declared like
int find_substring( const char * str_for_search_in, const char * substring);
It does not change the passed strings so its parameters should be declared with the qualifier const
. And the function should not output any message. It is the caller of the function will decide whether to output a message. The function just should return a value (0 or 1) that the caller of the function can check.
This for loop
for (int i = 0; i < strlen(str_for_search_in) - strlen(substring); i++)
at least has a wrong condition, You should write it like for example
for (int i = 0; i <= strlen(str_for_search_in) - strlen(substring); i++)
But this work only in case when strlen(str_for_search_in)
is indeed greater than or equal to strlen(substring)
.
Also there are redundant calls of strlen
.
Character arrays do not have member functions. So this expression
str_for_search_in.substr(i, strlen(substring))
is invalid.
And to compare strings in your for loop you need to use standard C string function strncmp
declared in the header <string.h>
.
Pay attention to that within your function you could use standard C string function strstr
for example the following way
int find_substring( const char * str_for_search_in, const char * substring)
{
return strstr( str_for_search_in, substring ) != NULL;
}