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 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With