0

I need to find all string definitions in a C project that contains a certain word.

For example given a file called test.c :

int main(int argc, char** argv)
{
  int hello = 0;
  string str = "hello world";
  printf(str); 

  return 0;
}

Expected:

print(check_code_for_word_in_str('test.c','hello'))
>>> ./test.c:4: string str = "hello World";

Would be nice if the line number where the string is found is also displayed. Note how the variable hello = 0 is not printed.

I've checked similar things with ats parsing python code. But no idea how to do for c code.

Julian Fondren
  • 5,459
  • 17
  • 29
EricPb
  • 560
  • 1
  • 8
  • 21

2 Answers2

0

Try doing the following:

grep -nE "\"[^\"]*hello[^\"]*\"" *.c

The output in your case is:

test.c:4:  string str = "hello world";

It looks for places where the word 'hello' appears after the beginning of a string, but before the string was closed. It's probably not perfect, but it might be good enough for your use-case.

Roy2012
  • 11,755
  • 2
  • 22
  • 35
  • Thanks, but the word could be in any location of the string. Maybe a multiple line string as well, would that still work? – EricPb Jun 17 '20 at 07:15
  • will work in any location in the string. Multi-line strings - depending on how they are built. – Roy2012 Jun 17 '20 at 07:17
  • Thanks but it works partially, it will also return a result with this case: `syslog("The result is:%d", hello_var);`. The `hello_var` is not a string but a variable. – EricPb Jun 23 '20 at 07:53
  • Improved the solution a bit. Note that it's still not perfect - won't work for multiline strings, for example. – Roy2012 Jun 23 '20 at 10:35
0

if there is multiple line string, then you can separate the string into an array of string which we can build by traversing the original string and storing it in the array and when '\n' comes then we increment the index and store it in the next array element, this can help us to identify on which line the word has occurred.

Then to find the ford we can traverse each of the array elements and traverse each of the whole string and compare it with the respective word, You can use two pointer algorithm to compare(one for traversing and other for the word) because for using strcmp() we need to split the array or separate out the words, in two pointer algo when the second pointer reaches the end of word then we can print the index+1 which is the line and "found" or we can also store it in the count to know how many times word occurred in the specific line.

VR7
  • 112
  • 3
  • 16