The Program in C# Program to Find the longest word in String is given below:
using System;
namespace LongestWord
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family, enter a string here to find the longest word: ");
string inputString = Console.ReadLine();
string[] words = inputString.Split(' ');
string longestWord = "";
foreach (string word in words)
{
if (word.Length > longestWord.Length)
{
longestWord = word;
}
}
Console.WriteLine("Okay, the longest word in the string is: " + longestWord);
}
}
}
Output:
Hello Codeauri Family, enter a string here to find the longest word:
keep coding with codeauri
Okay, the longest word in the string is: codeauri
Pro-Tips💡
Here are the step by step execution of above program are:
- The first line “using System;” is a directive that brings the System namespace into scope and makes its classes and methods available to the code.
- The namespace declaration “namespace LongestWord” creates a new namespace with the name “LongestWord”.
- The class declaration “class Program” creates a new class with the name “Program”.
- The “Main” method is the entry point of the application. It prints a message to the console asking the user to enter a string and then reads the input string from the console using Console.ReadLine().
- The code splits the input string into individual words using the string method “Split” and stores the words in an array “words”.
- The code declares a string variable “longestWord” and initializes it to an empty string.
- The code uses a “foreach” loop to iterate over the words in the “words” array. For each word, the code checks if its length is greater than the length of the “longestWord”. If it is, the code sets “longestWord” to the current word.
- After the loop finishes, the code writes the “longestWord” to the console as the result.