Reputation: 1
I'm trying to write a function that extracts the comment out of a string. For example, given:
"this is a test //bread is great"
it returns:
"bread is great"
I've tried to count the characters until the first '//
' appears and then trim the unwanted part of the string.
while(s[i] != '/' && s[i+1] != '/') {
newbase++;
i++;
}
It worked for the first example but I'm having issues if I'm given a string like this:
"int test = 2/3"
It should return ""
(an empty string) but it doesn't. I don't understand it.
Upvotes: 0
Views: 59
Reputation: 213892
This is very basic string handling. Simply use strstr
and if successful, use the result. Optionally copy it to a second string.
#include <stdio.h>
#include <string.h>
int main (void)
{
const char* str = "this is a test //bread is great";
const char* result = strstr(str,"//");
if(result != NULL)
{
result += 2; // skip the // characters
puts(result); // print the string
// optionally make a hardcopy
char some_other_str[128];
strcpy(some_other_str, result);
puts(some_other_str);
}
}
Upvotes: 2
Reputation: 50774
If you just want to extract naively the remaining string after the first occurence of "//"
you probably need something like this:
#include <stdio.h>
#include <string.h>
int main()
{
const char *text = "this is a test //bread is great";
const char* commentstart = strstr(text, "//");
char comment[100] = { 0 }; // naively assume comments are shorter then 99 chars
if (commentstart != NULL)
{
strcpy(comment, commentstart + 2);
}
printf("Comment = \"%s\"", comment);
}
Disclaimers:
Upvotes: 0