Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to find the index/ or position of the word that my program found to be the longest in the string

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);

}
 }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading