Home > Mobile >  I want to find the index/ or position of the word that my program found to be the longest in the str
I want to find the index/ or position of the word that my program found to be the longest in the str

Time:05-24

This is my code, I am taking input from user, I want to find out the index/ or position of the longest word in the string the user is typing. I can't seem to figure this out! Wherever I try to find help, I get indexOf() method in which you manually have to type the word of which you are trying to find index.

This is my code:

using System;
using System.Linq;

public class Question1
{
public static void Main(string[] args)
{
   
    Console.WriteLine("Enter String:");
    string line = Console.ReadLine();
    string[] words = line.Split(new[] { " " }, StringSplitOptions.None);
    string word = "";
    int ctr = 0 , len, max = 0;
    
    foreach (String s in words)
    {
        if (s.Length > ctr)
        {
            word = s;
            ctr = s.Length;
           

        }

    }
    Console.WriteLine("Longest String : "   word);
    Console.WriteLine("Length : "   ctr);

}
 }

CodePudding user response:

To find longest word index from a sentence you have to use .indexOf() method from Array class.

Instead of

Console.WriteLine(word.IndexOf(word, ctr));

Try,

int longestWordIndex = Array.IndexOf(words, word);
Console.WriteLine($"Index of Longest word = {longestWordIndex}");

CodePudding user response:

You can find the index of the word you've found like this:

int indexOfWord = line.IndexOf(word, StringComparison.CurrentCulture);

So if the word is the first word, indexOfWord will be 0. If it's "William" in "Hello William", then it will be 6, etc.

Try it online

CodePudding user response:

Validation of punctuation and other characters aside:

const string sentence = "Find the position of the longest word in this sentence";

var longestWord =
   sentence
      .Split(' ')
      .OrderByDescending(w => w.Length)
      .First();

var position = sentence.IndexOf(longestWord, StringComparison.InvariantCulture);

CodePudding user response:

In general case, we should come to terms: what word is. If we agree that

Word is a non-empty sequence of letters and apostrophes

we can match words with a help of regular expessions and then query matches to obtain the longest one with a help of Linq. Please, note, that in general case (with punctuations) Split is not enough.

Code:

using System.Linq;
using System.Text.RegularExpressions;

...

string line = 
  "This is the sentence; it has some punctuations! ---note-it's-not-the-longest--";

var result = Regex
  .Matches(line, @"[\p{L}'] ")
  .Cast<Match>()
  .MaxBy(match => match.Value.Length);

Console.Write(
  $"Word is \"{result.Value}\" at postion {result.Index} (length {result.Length})"
);

Outcome:

Word is "punctuations" at postion 34 (length 12)
  • Related