[SOLVED] Longest word in string


How can I find length of longest word in const char string without using auxiliary string?

#include <stdio.h>

int longest(const char *str) {
    int max = 0, prev = 0, final_max = 0;
    while (*str != '\0') {
        prev = max;
        max = 0;
        while (1) {
            if (*str != ' ') 


            if (*str == ' ') 
        if (prev > max)
            final_max = prev;

  return final_max;

void main() {
    const char str[] = "Longest word in string";
    printf("%d", longest(str));

This prints 4 as length of longest word. Could you help me fix this?


You can find the longest word in linear time. This is surely optimal since any algorithm has to process every character at least once.

The basic idea is to loop over every character of the string, keeping track of the position of the last space (or any other word separator). Everytime the current character is a space we update the answer.

Note that we need to add an extra check at the end for the case where the longest word is the last in the string (and thus is not necessarily followed by a space).

Here’s a simple implementation:

#include <stdio.h>

size_t longest(const char *str) {
  size_t i, last=-1, ans=0;
  for (i = 0; str[i] != '\0'; i++)
    if (str[i] == ' ') {
      if (ans < i-last) ans = i-last-1;
      last = i;
  if (ans < i-last) ans = i-last-1;
  return ans;

void main(){
  printf("%zu\n", longest("Longest word in string")); // 7

Answered By – heitor

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *