How to split a string by newline in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

/**
 * Splits a string by newline characters and processes each line 
 * without modifying the original string (non-destructive).
 *
 * @param str The null-terminated input string to split.
 */
void split_by_newline(const char *str) {
    // Guard clause: check for NULL pointer input
    if (str == NULL) {
        return;
    }

    const char *start = str;
    const char *end = NULL;
    int line_num = 1;

    // Iterate through the string until the null terminator is reached
    while (*start != '\0') {
        // Find the next occurrence of the newline character
        end = strchr(start, '\n');

        if (end != NULL) {
            // Print the segment from 'start' to 'end' using precision width (%.*s)
            // This safely prints the substring without requiring a temporary null-terminated buffer.
            printf("Line %2d: %.*s\n", line_num++, (int)(end - start), start);
            
            // Move the start pointer past the newline character for the next iteration
            start = end + 1;
        } else {
            // Handle the final line (which may not end with a newline character)
            printf("Line %2d: %s\n", line_num++, start);
            break;
        }
    }
}

int main() {
    // Best practice: Can use a string literal since the function doesn't modify it
    const char *multiline_text = "Hello world!\nThis is line two.\nFinal line here.";

    split_by_newline(multiline_text);

    return 0;
}


/*
run:

Line  1: Hello world!
Line  2: This is line two.
Line  3: Final line here.

*/

 



answered 21 hours ago by avibootz
...