What is a good way of looping through lines in a multi
My function foo(char *str)
receives 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 getLine
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.
I think you might use strtok
, which tokenizes a string into packets delimited by some specific characters, in your case the newline character:
void foo(char *str)
{
char *line = strtok(str, "n");
while(line)
{
//work with line, which contains a single line without the trailing 'n'
...
//next line
line = strtok(NULL, "n");
}
}
But keep in mind that this alters the contents of str
(it actually replaces the 'n'
s by '