Advertisement
Guest User

Longest Word

a guest
Dec 7th, 2016
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. // Complete the longestWord function
  2. // The function should return a pointer to the longest word in the
  3. // provided string. If two words are of equal length, return a pointer
  4. // to the word that occurs first.
  5.  
  6. // For the task, you may assume a word is made of alphabetic characters.
  7. // If no words are found, return a NULL pointer
  8.  
  9. // You may use C library functions
  10.  
  11. // To compile your code, run:
  12. // gcc -Wall -Werror -o ? longestWord.c longestWord_?.c
  13. // Replace the question mark with the test you wish to compile
  14. // Solutions can be found in the corresponding .out file
  15.  
  16. #include <stdlib.h>
  17. #include <ctype.h>
  18. #include <string.h>
  19.  
  20. #include "longestWord.h"
  21.  
  22. char* longestWord(char* string){
  23.     char lWord[1000];
  24.     int lWordLength = 0;
  25.  
  26.     char currWord[1000] = {};
  27.     int currWordLength = 0;
  28.  
  29.     for (int i = 0; i < strlen(string); i++) {
  30.         char c = string[i];
  31.         if (isalpha(c)) {
  32.             strncat(currWord, &c, 1);
  33.             currWordLength++;
  34.         } else {
  35.             if (currWordLength > lWordLength) {
  36.                 strcpy(lWord, currWord);
  37.                 lWordLength = currWordLength;
  38.             }
  39.             currWord[0] = '\0';
  40.             currWordLength = 0;
  41.         }
  42.     }
  43.  
  44.     string = lWord;
  45.     return string;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement