首页 > 解决方案 > 在没有拆分、不同和 foreach 的情况下查找字符串中最长的单词(并将其写出来)

问题描述

我得到了一项任务,要制定一种方法来查找字符串中最长的单词,而无需拆分、不同和 foreach。

我能够拆分单词并计算长度,但我被困在如何实际比较和写出它们。

static void Main(string[] args)
{
    String s1 = "Alex has 2 hands.";
    longestWord(s1);
    Console.
}

static void longestWord(String s1)
{
    char emp = ' ';
    int count = 0;
    char[] ee = s1.ToCharArray();
    for (int i = 0; i < ee.Length; i++)
    {
        if (ee[i] == emp || ee[i] == '.')
        {
            count++;
            Console.Write(" " + (count-1));
            Console.WriteLine();
            count = 0;
        }
        else
        {
            Console.Write(ee[i]);
            count++;
        }
    }
} 

现在的输出如下所示:

Alex 4
has 3
2 1
hands 5

我很确定我只能通过将重置前的计数与 temp int 进行比较来获得最长的数字,但如何用它写出单词。

或者,如果有更简单的方法可能是。

标签: c#arrayschar

解决方案


你已经走在了一条好路上。不是直接打印单词,而是存储最长单词的长度和位置,并在末尾打印。像这样:

static void longestWord(String s1)
{
    char emp = ' ';

    int longestLength = 0;
    int longestStart = 0;

    int currentStart = 0;

    for (int i = 0; i < s1.Length; i++)
    {
        if (s1[i] == emp || s1[i] == '.')
        {
            // calculate the current word length
            int currentLength = i - currentStart;

            // test if this is longer than the currently longest
            if(currentLength > longestLength)
            {
                longestLength = currentLength;
                longestStart = currentStart;
            }

            // a new word starts at the next character
            currentStart = i + 1;                     
        }
    }

    // print the longest word
    Console.WriteLine($"Longest word has length {longestLength}: \"{s1.Substring(longestStart, longestLength)}\"");
}

没有必要.ToCharArray()。您可以直接访问字符串。


推荐阅读