Reputation: 79
I have written a while loop to run until it find */
. But unfortunately my loop is exiting as soon as it finds a single *
itself .
while (str[++i] != '*' && str[++i] !='/' );
Any help would be greatly appreciated. Thank You.
Upvotes: 1
Views: 120
Reputation: 8830
What about using the function:
char *strstr(const char *s1, const char *s2);
char *substr = strstr ( &str[i], "*/" );
I don't know what your bigger picture is but usually parsing is done by breaking up 'keywords' separated by 'white space' into an array of tokens. "*/" would then be one of your tokens. You might find the C function strtok worth checking out.
Upvotes: 2
Reputation: 33273
there are several problems with this construct:
while (str[++i] != '*' && str[++i] !='/' );
*
or a /
is found.You can do it like this:
while (str[i]) {
if (str[i] == '*' && str[i+1] =='/' ) {
break;
}
i++
}
Upvotes: 3
Reputation: 21223
Looking at your loop condition and at what you expect the code to do, it is clearly wrong. A while loop stops as soon as its condition is false, this means that it will stop when this is true:
!(str[++i] != '*' && str[++i] !='/')
Which is the same as (str[++i] == '*' || str[++i] =='/')
. It stops as soon as it hits a *
because of short circuit evaluation. Also, the double increment side-effects are quite subtle to handle and can lead to hard to track bugs.
You are also missing the check for end of string. I'd advice to do something like:
while (str[i] != '\0' && !(str[i] == '*' && str[i+1] =='/')) {
i++;
}
Or, equivalently,
for (; str[i] != '\0' && !(str[i] == '*' && str[i+1] =='/'); i++)
; /* Intentionally left blank. */
Upvotes: 6