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 '' s), so you may want to make a copy of it beforehand if you need it further.


Sooo... a bit late, but below is a re-entrant version of @debeer's and @Christian Rau's answer - notice strtok_r instead of strtok . This can be called from multiple threads using different strings.

char *tok;
char *saveptr;
char *delims = "n";
tok = strtok_r(str, delims, &saveptr);

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

  //advance the token
  tok = strtok_r(NULL, delims, &saveptr);
}

Please note that it is still destructive as it modifies the string being tokenised.

链接地址: http://www.djcxy.com/p/56640.html

上一篇: 你可以使用Java Annotations来评估方法中的某些东西吗?

下一篇: 循环多行代码的好方法是什么?