The Program in C to display the biggest name in an entered string inputted by user is given below:
#include <stdio.h>
#include <string.h>
int main() {
char str[1000], word[20], max_word[20];
int i, j, len, max_len = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
len = strlen(str);
j = 0;
for (i = 0; i <= len; i++) {
if (str[i] != ' ' && str[i] != '\0' && str[i] != '\n') {
word[j++] = str[i];
}
else {
word[j] = '\0';
if (strlen(word) > max_len) {
max_len = strlen(word);
strcpy(max_word, word);
}
j = 0;
}
}
printf("The longest word is: %s\n", max_word);
return 0;
}
Output:
Enter a string: yes that was fun evening to learn from codeauri
The longest word is: codeauri
Pro-Tips💡
In this code, fgets(str, sizeof(str), stdin)
is used to read the string from the user, the sizeof(str) is used to specify the maximum size of the string to be read,
and stdin
is used to specify that input should be read from the standard input.
Also, the condition of the if statement is changed to check for the newline character ‘\n’ as well.
By using fgets()
instead of gets()
, this program is now more secure and less likely to suffer from buffer overflow errors.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.