I'm coding for a function that checks the longest word (or words) in a string:
- If multiple words are of the same size, those words have to be displayed.
- If a single word is inputted, that word has to be displayed.
- Words should consist only of alphabets.
The following code has been tested and displays the correct input for the above conditions:
//this method returns the longest word (or words) of a single string
static void longestWord(string s)
{
int j = 0, k = 0, l = 0, tempLength = 0, maxLength = 0;
List<int> indexList = new List<int>();
char[] words = s.ToCharArray();
StringBuilder longestWord = new StringBuilder();
//a for loop to ignore spaces at the beginning of the string
for (int i = 0; i <= s.Length - 1; i++)
{
if (((words[i] >= 'A' && words[i] <= 'Z') || (words[i] >= 'a' && words[i] <= 'z')))
{
j = i;
l = i;
break;
}
}
//a for loop to get the maximum length of the longest word
for (; j <= s.Length - 1; j++)
{
if (((words[j] >= 'A' && words[j] <= 'Z') || (words[j] >= 'a' && words[j] <= 'z')))
{
tempLength++;
if (j == (s.Length - 1))
{
if (tempLength >= maxLength)
{
maxLength = tempLength; //this ensures the maximum length of a single word is captured
//removing this will not display single words without non-alphabets
}
}
}
else
{
if (tempLength >= maxLength)
{
maxLength = tempLength;
}
tempLength = 0;
}
}
tempLength = 0;
//a for loop to add the longest words into a list
for (; l <= s.Length - 1; l++)
{
if (((words[l] >= 'A' && words[l] <= 'Z') || (words[l] >= 'a' && words[l] <= 'z')))
{
tempLength++;
if (l == (s.Length - 1))
{
if (tempLength >= maxLength)
{
indexList.Add(l+1); //'l+1' ensures a word that has no non-alphabet after it is captured
//removing l+1 displays as 'wanted remov' - 'e' is missing
k++;
}
}
}
else
{
if (tempLength == maxLength)
{
indexList.Add(l);
k++;
}
tempLength = 0;
}
}
//a for loop to append the longest words into a single word
for (int m = 0; m <= k - 1; m++)
{
for (int n = (indexList[m] - maxLength); n < indexList[m]; n++)
{
longestWord.Append(words[n]);
}
longestWord.Append(" ");
}
Console.WriteLine(longestWord);
}
Honestly, although this code works, I'm unsatisfied with it and would like suggestions as to how I could improve it lengthwise and in readability.