Legend Legend - 2 months ago 8
C Question

What is a good way of looping through lines in a multi-line string?

My function

foo(char *str)
that is a multiline string with new line characters that is null-terminated. I am trying to write a while loop that iterates through the string and operates on one line. What is a good way of achieving this?

void foo(char *str) {
while((line=getLine(str)) != NULL) {
// Process a line

Do I need to implement
myself or is there an in-built function to do this for me?


You will need to implement some kind of parsing based on the new line character yourself. strtok() with a delimiter of "\n" is a pretty good option that does something like what you're looking for but it has to be used slightly differently than your example. It would be more like:

char *tok;
char *delims = "\n";
tok = strtok(str, delims);

while (tok != NULL) {
  // process the line

  //advance the token
  tok = strtok(NULL, delims);

You should note, however, that strtok() is both destructive and not threadsafe.