0

hi every one. i want some help in writing the code to find out shortest word in a string. i am posting a code on longest word. can somebody help me in writing this code?

this is the code for longest word in a string without any built in function

#include<stdio.h>
#include<conio.h>
void main()
{
int i,max=0,count=0,j;
char str[100]; 
clrscr();
printf("\nEnter the string\n:");
gets(str);
for(i=0;str[i]!='\0';i++)
{
if(!(str[i]==' '))
{
count++;
}
else
{
if(max<count)
{
j=i-count;
max=count;
}
count=0;
}
}
if(max<count)
{ 
j=i-count; 
max=count; 
} 

for(i=j;i<(j+max);i++)
printf("%c",str[i]); 
getch(); 
}
3
Contributors
2
Replies
20
Views
2 Years
Discussion Span
Last Post by sunktugg
1

This is how I would go about it.

Shortest word version:

#include <stdio.h>

void main() {
  char str[100], *ptr = str, *p_word = str, *p_best = str;
  unsigned count = 0, count_best = sizeof(str);

  // Fetch input
  printf("\nEnter the string: ");
  gets(str);

  do {
    // !(value & ~32) will match 0x00 (termination) or 0x20 (space)
    if(!(*ptr & ~32)) {
      // compare and remember best match
      if(count < count_best) {
        count_best = count;
        p_best = p_word;
      }
      count = 0;
    } else if(!count++) p_word = ptr; // count characters
  } while(*ptr++ != 0);

  // Print output
  for(ptr = p_best; (*ptr & ~32); ) putch(*ptr++);
}

Longest word version:

void main() {
  char str[100], *ptr = str, *p_word = str, *p_best = str;
  unsigned count = 0, count_best = 0;

  // Fetch input
  printf("\nEnter the string: ");
  gets(str);

  do {
    // !(value & ~32) will match 0x00 (termination) or 0x20 (space)
    if(!(*ptr & ~32)) {
      // compare and remember best match
      if(count > count_best) {
        count_best = count;
        p_best = p_word;
      }
      count = 0;
    } else if(!count++) p_word = ptr; // count characters
  } while(*ptr++ != 0);

  // Print output
  for(ptr = p_best; (*ptr & ~32); ) putch(*ptr++);
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.