Advertisements
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);
}
}
>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.