Find the longest word in the string c

Don’t split the string, use a Regex

If you care about performance you don’t want to split the string. The reason in order to do the split method will have to traverse the entire string, create new strings for the items it finds to split and put them into an array, computational cost of more than N, then doing an order by you do another (at least) O(nLog(n)) steps.

You can use a Regex for this, which will be more efficient, because it will only iterate over the string once

var regex = new Regex(@"(w+)s",RegexOptions.Compiled);
var match = regex.Match(fileText);
var currentLargestString = "";

while(match.Success)
{
     if(match.Groups[1].Value.Length>currentLargestString.Length)
     {
         currentLargestString = match.Groups[1].Value;
     }

     match = match.NextMatch();
}

The nice thing about this is that you don’t need to break the string up all at once to do the analysis and if you need to load the file incrementally is a fairly easy change to just persist the word in an object and call it against multiple strings

If you’re set on using an Array don’t order by just iterate over

You don’t need to do an order by your just looking for the largest item, computational complexity of order by is in most cases O(nLog(n)), iterating over the list has a complexity of O(n)

var largest = "";
foreach(var item in strArr)
{
    if(item.Length>largest.Length)
        largest = item;
}

A word is a consecutive non-whitespace character set. The C program here will find out the longest word in a given string. If multiple words are present with the same length of the longest one, it will print the first one.

#include <stdio.h>
#include <string.h>

#define MAX_STRING_LEN 1024

int main(){
  char str[MAX_STRING_LEN];
  char longest_str[MAX_STRING_LEN];
  int len;
  int i, index = 0;
  int max_wlen = 0, wlen = 0;
  
  printf("Enter a string: ");
  gets(str);
  
  len = strlen(str);
  
  for (i = 0; i <= len; i++) {
  
    if (str[i] != ' ' && str[i] != '') {
      wlen++;
      continue;
    }
    
    /* space or end of string */
    if (wlen > max_wlen) {
      max_wlen = wlen;
      index = i - max_wlen;
    }
    
    wlen = 0;
  }
  
  for (i = 0; i < max_wlen; i++) {
    longest_str[i] = str[index+i];
  }
  
  longest_str[i] = '';
  
  printf ("Longest word: %s.n", longest_str);
  printf ("Longest word length: %d.n", max_wlen);
  return 1;
}

This program takes a string as input. The first ‘for‘ loop traverses all the characters in the string. This loop has one extra iteration than the length of the string – to consider the last word.

The wlen variable tracks the current word length and max_wlen tracks the longest word length so far.

For every non-whitespace character, the current word length, wlen, is increased by 1.

A whitespace character is considered as a possible end of a word – unless the previous character is also a whitespace.

If a whitespace character is encountered and the current word is longer than the longest word so far (wlen > max_wlen), current word length is set as the longest one. The index variable is set as the starting index of the longest word so far. For every whitespace character wlen is reset to o – to start a fresh count for the next word.

When the first loop ends, the index becomes the starting index of the longest word. And max_wlen becomes the length of the longest word.

The second ‘for‘ loop copies the longest word to another string, longest_str. At the end the program prints the longest word with it length.

The program output:

$ ./test
Enter a string: Optimism is an occupational hazard of programming
Longest word: occupational.
Longest word length: 12.

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.
View all posts by Srikanta

If you also want to contribute, click here.

Why do you have more parenthesis than needed in this statement?

if (((words[j] >= 'A' && words[j] <= 'Z') || (words[j] >= 'a' && words[j] <= 'z')))
if ((words[j] >= 'A' && words[j] <= 'Z') || (words[j] >= 'a' && words[j] <= 'z'))

Similarly:

if (l == (s.Length - 1))

Should be written as:

if (l == s.Length - 1)

As well:

for (int n = (indexList[m] - maxLength); n < indexList[m]; n++)

Should be:

for (int n = indexList[m] - maxLength; n < indexList[m]; n++)

Using j, k and l as a variable in this manner is frowned upon. These should only ever be used with local iterators. (I.e. where you have i.)


Some of your names are not idiomatic.

char[] words = s.ToCharArray();

Should be:

char[] characters = s.ToCharArray();

The string s parameter should be string input (et. al.).


You can take some of your operations to functions, delegates, Lambdas, etc.

if (((words[l] >= 'A' && words[l] <= 'Z') || (words[l] >= 'a' && words[l] <= 'z')))

Can more easily be written as a delegate, function, etc.

if (IsAlphaChar(words[l])

Use a foreach loop in place of:

for (int m = 0; m <= k - 1; m++)

Should be:

foreach (int index in indexList)

Then just use index in place of indexList[m].


Never do this:

int j = 0, k = 0, l = 0, tempLength = 0, maxLength = 0;

That is a readability nightmare. Break each variable to it’s own line. (And don’t declare all of them in one spot. Declare them when you need them.)


You shouldn’t declare iterators outside a for loop. (I’m looking at you, j and l.)


Doing words[i] four times is slower than char currentCharacter = words[i];. (Of course, the location that is used should be a method instead.)


You don’t use j or l after their respective loops, so don’t define them as the first thing in the method. Instead, define them as:

for (int j = i; j <= s.Length; j++)
for (int l = i; l <= s.Length; l++)

 Problem statement:- Program to Find the Longest word in a string.

Example:-

              Input: Given

                                 String=Find the Longest word in string

             Output: Longest Substring(Word) is Longest. 

            Input: Given

                                 String=C++ string questions

             Output: Longest Substring(Word) is questions

Data requirement:-

   Input Data:- str

  Output Data:-
sub_str


  Additional Data:- 
in,out,p,len1,maxInd,max

Program in C

Here is the source code of the C Program to Find the Longest word in a string.

Code:

#include<stdio.h>

#include<string.h>

main()

{

    int in=0,out=0,p=0,len1,maxInd=0,max=0;

    char str[100]={0},sub_str[100][100]={0};

    printf(«Enter your String:»);

    gets(str);

    //splitting Input String into sub string

    while(str[p]!=»)

    {

        out=0;

        while(str[p]!=’ ‘&&str[p]!=»)

        {

            sub_str[in][out]=str[p];

            p++;

            out++;

        }

        sub_str[in][out]=»;

        in++;

        if(str[p]!=»)

        {

            p++;

        }

    }

    int len=in;

    max=strlen(sub_str[0]);

    //finding max length of Substring from splitting string length

        for(in=0;in<len;in++)

        {

            len1=strlen(sub_str[in]);

            if(len1>max)

            {

                max=len1;

                maxInd=in;

            }

        }

        printf(«Longest Substring(Word) is %sn»,sub_str[maxInd]);

}

Input/Output:

Enter your String:Find the Longest word in a string

Longest Substring(Word) is Longest

Program in C++

Here is the source code of the C++ Program to Find the Longest word in a string.

Code:

#include<iostream>

#include <cstring>

using namespace std;

main()

{

    int in=0,out=0,p=0,len1,maxInd=0,max=0;

    char sub_str[100][100]={0};

    string str;

    cout<<«Enter your String:»;

    getline(cin,str);

    //splitting Input String into sub string

    while(str[p]!=»)

    {

        out=0;

        while(str[p]!=’ ‘&&str[p]!=»)

        {

            sub_str[in][out]=str[p];

            p++;

            out++;

        }

        sub_str[in][out]=»;

        in++;

        if(str[p]!=»)

        {

            p++;

        }

    }

    int len=in;

    max=strlen(sub_str[0]);

    //finding max length of Substring from splitting string length

        for(in=0;in<len;in++)

        {

            len1=strlen(sub_str[in]);

            if(len1>max)

            {

                max=len1;

                maxInd=in;

            }

        }

        cout<<«Longest Substring(Word) is «<<sub_str[maxInd]<<«n»;

}

Input/Output:

Enter your String:C++ string questions

Longest Substring(Word) is questions

Program in Java

Here is the source code of the Java Program to Find the Longest word in a string.

Code:

import java.util.Scanner;

public class LongestSubstring {

public static void main(String[] args) {

Scanner cs=new Scanner(System.in);

String str1;

System.out.println(«Enter your String:»);

str1=cs.nextLine();

str1+=» «;

//splitting Input String into sub string

String[] sub_str=str1.split(«\s»);

int in,len1,maxInd=0,max=0;

  //finding max length of Substring from splitting string length

    int len=sub_str.length;

    max=sub_str[0].length();

        for(in=0;in<len;in++)

        {

            len1=sub_str[in].length();

            if(len1>max)

            {

                max=len1;

                maxInd=in;

            }

        }

       System.out.print(«Longest Substring(Word) is «+sub_str[maxInd]+»n»);

    cs.close();

}

}

Input/Output:

Enter your String:

string program in java 

Longest Substring(Word) is program

Program in Python

Here is the source code of the Python Program to Find the Longest word in a string.

Code:

str=input(«Enter Your String:»)

sub_str=str.split(» «)

maxInd=0

max=0

max = len(sub_str[0])

for inn in range(0,len(sub_str)):

    len1 = len(sub_str[inn])

    if len1 > max:

        max=len1

        maxInd=inn

print(«Longest Substring(Word) is «,sub_str[maxInd])

Input/Output:

Enter Your String:Python String Program

Longest Substring(Word) is  Program

How to print the longest word of a string in C:

In this post, we will learn how to print the longest word of a string in C. The program will take one string as input from the user and print the longest word of the string.

With this post, you will learn how to read a string in C, how to iterate through the characters of a string and how to find and print the longest word.

C program:

Let’s write down the program first:

#include <stdio.h>

int main()
{
    int length = 0;
    int longestLength = 0;
    int endIndex = 0;
    int i, j;

    char str[100];
    char word[100];

    // read the string
    printf("Enter a string:n");
    scanf("%[^n]", str);

    // iterate through the characters
    for (i = 0; str[i] != ''; i++)
    {
        if (str[i] != ' ')
        {
            length++;
            continue;
        }

        if (length > longestLength)
        {
            longestLength = length;
            endIndex = i;
        }

        length = 0;
    }

    if (length > longestLength)
    {
        longestLength = length;
        endIndex = i;
    }

    // copy the longest word
    j = 0;
    for (i = endIndex - longestLength; i < endIndex; i++, j++)
    {
        word[j] = str[i];
    }
    word[j] = '';

    printf("Longest word: %sn", word);

    return 0;
}

Here,

  • length is a variable to hold the current length of the word. The program will iterate through the characters of the string and this variable will hold the length of the current word.
  • longestLength is to hold the length of the longest word and endIndex is to hold the index of the character just after the end character of the longest word. So the longest word will start at index endIndex — longestLength and ends at endIndex — 1
  • i and j are two variables to use in the loops.
  • str and word are two character arrays to hold the user input string and the longest word.
  • It uses printf to ask the user to enter a string and by using scanf, it reads the string and stores that in the character array str.
  • The for loop iterates through the characters of the array one by one.
    • If the current character is a blank character, it increases the value of length by 1. The continue statement moves it to the next iteration and ignores the next steps.
    • If the current character is not a blank character, i.e. it reaches the end of a word. It checks if the length of the word calculated is more than the longest length or not. If yes, assign the current value as the longest length, assign the current value of i to endIndex.
    • Also, reset the value of length to 0.
  • After the for loop ends, compare the value of length one more time with longestLength. This check is for the last word of the string. If length is greater than longestLength, assign the value of length to longestLength and assign i to endIndex.
  • The next for loop is used to copy the longest word from the user input string str to the string word. It starts from endIndex — longestLength and ends at endIndex — 1. It copies all characters from str to word.
  • The final printf statement prints the longest word, i.e. word.

Output:

Let’s see how it works:

Enter a string:
hello universe
Longest word: universe

Enter a string:
hello world and universe
Longest word: universe

Enter a string:
hello a ab abc abcd !!
Longest word: hello

C print longest word in string

As you can see here, it prints the longest word each time.

Conclusion:

In this post, we learned how to print the largest word of a string. You can use the same algorithm with a little bit change to find the smallest word of a string. If you want to find the smallest word, you need to compare the current word length with a value that is used to store the smallest value. Similar to the above example, we can copy the word to a different string.

Понравилась статья? Поделить с друзьями:
  • Find ten places to go in the word search
  • Find ten kinds of film or tv programme in the word square
  • Find table name in word
  • Find synonyms to the given words and word combinations
  • Find synonyms in the texts for the word below