How to get the first line of a multi-line string in C

1 Answer

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

void getFirstLine(const char* multiLineString, char* firstLine) {
    const char* newline = strchr(multiLineString, '\n');
    
    if (newline != NULL) {
        size_t length = newline - multiLineString;
        strncpy(firstLine, multiLineString, length);
        firstLine[length] = '\0';
    } else {
        strcpy(firstLine, multiLineString);
    }
}

int main() {
    const char* multiLineString = 
        "First line\n"
        "Second line\n"
        "Third line\n"
        "Fourth line";
    
    char firstLine[256];
    
    getFirstLine(multiLineString, firstLine);
    
    printf("The first line is: %s\n", firstLine);
    
    return 0;
}


 
/*
run:
 
The first line is: First line
 
*/

 



answered Aug 12, 2024 by avibootz

Related questions

1 answer 102 views
1 answer 131 views
1 answer 123 views
1 answer 126 views
1 answer 112 views
1 answer 117 views
1 answer 112 views
...