Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

parsing

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?

like image 472
Legend Avatar asked Dec 01 '11 23:12

Legend


People also ask

How do I split a string into multiple lines?

You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.

What is the use of multiline string?

We can use single quotes (' '), double quotes (" "), and triple quotes (''' '''). Now, let us learn about the python multiline string. The python multiline string is used when the string is very long in size. It is used to keep text in a single line, but it affects the overall readability of the code.

What starts and ends a multiline string?

A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string.


1 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.

like image 166
dbeer Avatar answered Sep 29 '22 03:09

dbeer