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
CodePudding user response:
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;
}
CodePudding user response:
You were using std::string
which has substr
method, but now switched to raw-strings (char*
), that are plain data types. You can make use of pointer-arithmetic for a comparison.
In the same way, there is no operator==
for raw-strings (in this case you will be comparing pointers), in general prefer strcmp
, though in this case it may not be possible because your substrings may not end in a null character.
As a side note, take into consideration that strlen
has O(n) complexity, so calling it every time in your for loop is inefficient, pre-compute it.
I recommend you to take a look at string operations in C, rather than C .