Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Complete the longestWord function
- // The function should return a pointer to the longest word in the
- // provided string. If two words are of equal length, return a pointer
- // to the word that occurs first.
- // For the task, you may assume a word is made of alphabetic characters.
- // If no words are found, return a NULL pointer
- // You may use C library functions
- // To compile your code, run:
- // gcc -Wall -Werror -o ? longestWord.c longestWord_?.c
- // Replace the question mark with the test you wish to compile
- // Solutions can be found in the corresponding .out file
- #include <stdlib.h>
- #include <ctype.h>
- #include <string.h>
- #include "longestWord.h"
- char* longestWord(char* string){
- char lWord[1000];
- int lWordLength = 0;
- char currWord[1000] = {};
- int currWordLength = 0;
- for (int i = 0; i < strlen(string); i++) {
- char c = string[i];
- if (isalpha(c)) {
- strncat(currWord, &c, 1);
- currWordLength++;
- } else {
- if (currWordLength > lWordLength) {
- strcpy(lWord, currWord);
- lWordLength = currWordLength;
- }
- currWord[0] = '\0';
- currWordLength = 0;
- }
- }
- string = lWord;
- return string;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement