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

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?

Answers


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


Need Your Help

javascript/jquery - add debounce (throttle) to a button

javascript jquery throttle

I want to add a debounce (throttle) to a button, but i want to perform some actions each time user clicks button, but only after 5 second after user hits button, then perform SQL update. Usually the

Best way/pattern to build request based on different service

java python oop design-patterns refactoring

I have a about 20 different services which I have to send requests to which require a slightly different set of headers.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.