Home > Software design >  Is there a way to extract a comment out of a C string?
Is there a way to extract a comment out of a C string?

Time:12-09

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.

CodePudding user response:

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:

  • This is untested simple code that shows a possible approach. There is no error checking whatsoever, especially if the comment is longer than 99 chars, there will be a buffer overflow.
  • This code is absolutely not suitable for extracting comments from real life C code.

CodePudding user response:

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);
  }
}
  •  Tags:  
  • c
  • Related