How to get the length of the last word in a string with C

1 Answer

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

size_t lengthOfLastWord(char str[], char* words[]) {
    char delimiters[] = " ";
    int i = 0;

    words[i] = strtok(str, delimiters);
    while (words[i] != NULL) {
        i++;
        words[i] = strtok(NULL, delimiters);
    }

    return strlen(words[i - 1]);
}

int main(void)
{
    char str[256] = "c java c++ python c# c++ rust";
    char* words[32] = { '\0' };

    size_t len = lengthOfLastWord(str, words);

    printf("len = %zu", len);
}




/*
run:

len = 4

*/

 



answered May 4, 2024 by avibootz

Related questions

2 answers 144 views
1 answer 123 views
1 answer 123 views
1 answer 118 views
...