SCHOOL OF CODE BUILDERS
Learn To CODE. Become A DEVELOPER.
Pages
HOME
DATA STRUCTURES
STRINGS
ARRAYS
MATRIX
BINARY TREES
LINKED LIST
STACK
QUEUE
SORTING
SEARCHING
C
PYTHON
PSEUDOCODE
CONTEST PROBLEMS
ALGORITHMS
PATTERNS
PHP
C PUZZLES
C INTERVIEW QUESTIONS
JAVA
C++
HASHING
RECURSION
BASIC C PROGRAMS
TCS-CODEVITA
FACEBOOK
CONTACT US
C program to print longest word in a string
C program to print longest word in a string
Input:
Enter a sentence:
CodeRegister is a learning portal for computer science aspirants!
Output:
Longest word in the string is CodeRegister
Implementation:
#include
#include
#include
/* setting the maximum size for the character array */ #define MAX 1000000 /* user-defined function to find the length of the string or number of characters in the word here You can also use, strlen() function instead of slength() function */ int slength(char *s) { int i=0; /* traversing till last character of the string */ while(*(s+i)) { i++; //counting the size } /* returning the number of characters except null character ('\0') */ return i; } /* user-defined function to copy one string to another you can also use the strcpy() function which is a library function instead of using scopy() of this program */ void scopy(char *s,char *v) { int i=0; /* till we reach the end of source string copy all the characters one by one to the destination string */ while(*(v+i)) { *(s+i)=*(v+i); i++; } *(s+i)='\0'; /* mark the last character of destination string with null character ('\0') */ } int main(void) { char *s,*v[1000]; int i,spaces=1,j,k; /* allocate the memory for getting the input string */ s=(char*)malloc(sizeof(char)*MAX); printf("Enter a sentence:\n"); /* get the input string or sentence */ gets(s); /* To count the number of words in the given sentence number of words = number of spaces + 1 so, here counting the number of spaces in the sentence */ i=0; while(*(s+i)) { if(*(s+i)==' ') spaces++; i++; } /* allocate memory for the two dimensional array of strings */ for(i=0;i
PREVIOUS
NEXT
HOME