Reputation: 6034
So basically, I need to find out if a string begins with [URL]
and ends with [/URL]
.
Right now I'm doing:
const char *urlStart;
// ...
urlStart = strstr(message, "[URL]");
if (urlStart == NULL) {
urlStart = strstr(message, "[url]");
}
if (urlStart == NULL) {
return NULL;
}
According to cplusplus.com, "a pointer to the first occurrence in str1 of the entire sequence of characters specified in str2".
Does that mean I can just do this?
/*
* If the pointer to message is the same as urlStart,
* message begins with urlStart
*/
if (message != urlStart) {
return NULL;
}
// URL starts 5 characters after [URL]
urlStart += 5;
Initial testing seems to indicate that this doesn't work.
The complete function is located here.
Upvotes: 1
Views: 925
Reputation: 34839
Yes, the check if (message != urlStart)
will work as expected, assuming that message
begins with either [URL]
or [url]
. However if, for example, message
starts with [Url]
, then strstr
won't find the string because of case mismatch.
Given that you require the string to be at a known location in message
, the strstr
function really doesn't do much for you. It's simpler just to check the first 5 characters of message
, like this
char *start = "[URL]";
for ( int i = 0; i < 5; i++ )
if ( toupper(message[i]) != start[i] )
return NULL;
And you can check the [/URL]
at the end like this
length = strlen(message);
if ( length < 12 )
return NULL;
char *end = "[/URL]";
for ( int i = 0; i < 6; i++ )
if ( toupper(message[length-6+i]) != end[i] )
return NULL;
You could also use the non-case-sensitive-length-limited string compares, but note that those aren't portable. I believe it's strnicmp
on Windows, and strncasecmp
on unix clones.
Upvotes: 3