2

我试图根据长度找到最短和最长的字符串值,但我被卡住了。到目前为止,脚本在写入行之后退出。我认为代码需要一些帮助,我认为 for 循环不能单独工作。任何援助将不胜感激。

        for (int i = 5; i <0; i++)
        {
            string[] word = new string[5];
           Console.WriteLine("Type in a word");
            word[i] = Console.ReadLine();

             int length = word[i].Length;
             int min = word[0].Length;
             int max = word[0].Length;
             string maxx;
             string minn;


              if (length > max)
                 {
                   maxx = word[i];
                   Console.Write("Shortest");
                  }
             if (length < min) 
              {
                 minn = word[i];
                Console.Write("Longest");
              }



         }
        Console.ReadKey(true);
    }
4

9 回答 9

18

Linq 是让您的生活更轻松的方式...

var sorted=word.OrderBy(n => n.Length);
var shortest = sorted.FirstOrDefault();
var longest = sorted.LastOrDefault();
于 2013-08-23T04:06:18.537 回答
5

这是您可以使用的通用扩展方法(效率 O(n)):

public static class Extensions{
    // assumes that supply a Func<T, int> that will return an int to compare by
    public static Tuple<T, T> MaxMin<T>(this IEnumerable<T> sequence, Func<T, int> propertyAccessor){
        int min = int.MaxValue;
        int max = int.MinValue;

        T maxItem = default(T);
        T minItem = default(T);

        foreach (var i in sequence)
        {
            var propertyValue = propertyAccessor(i);
            if (propertyValue > max){
                max = propertyValue;
                maxItem = i;
            }

            if (propertyValue < min){
                min = propertyValue;
                minItem = i;
            }                       
        }

        return Tuple.Create(maxItem, minItem);
}

// max will be stored in first, min in second
var maxMin = word.MaxMin(s => s.Length);
于 2013-08-23T04:05:02.757 回答
4

尝试这个

    static void Main(string[] args)
    {
        string[] array1 = { "Cats and ratsasdfasdf", "just rats and the just catest", "rats" };
        var shortString = array1[0];
        var longString = array1[0];

        /*Code for Find Shortest and longest string in Array*/
        foreach (var t in array1)
        {
            if (shortString.Length > t.Length)
                shortString = t;
            if (longString.Length < t.Length)
                longString = t;
        }
        Console.WriteLine("shortest string is:" + shortString);
        Console.WriteLine("Longest string is:" + longString);
        Console.Read();
    }
于 2013-08-23T04:21:11.973 回答
1

您的 for 循环条件始终为假。i 从 5 开始,您正在检查它是否小于 0... 这总是错误的,因此循环永远不会开始。

如果这只是一个错字,那么您也将输入放入 names[i] 而不是 word[i],并且不再使用 names[i]...

于 2013-08-23T04:00:02.203 回答
1
string[] word = new string[5];
for (int i = 0; i <= word.Length; i++)
{

    Console.WriteLine("Type in a word");
    word[i] = Console.ReadLine();
}
int min = word[0].Length;
int max = word[0].Length;
string maxx = word[0];
string minn = word[0];
for (int i = 1; i <= word.Length; i++)
{
    int length = word[i].Length;
    if (length > max)
    {
        maxx = word[i];
        max = length;
    }
    if (length < min)
    {
        minn = word[i];
        min = length;
        Console.Write("Longest");
    }
}
Console.Write("Shortest:" + maxx);
Console.Write("Longest" + minn);
Console.ReadKey(true);
于 2013-08-23T04:08:00.457 回答
1

如果您使用 LINQ,则使用 Max/Min 方法是比排序更好的方法。

var longest = word.Max(s=>s.Length);
var shortest = word.Min(s=>s.Length);
于 2013-08-23T05:07:57.993 回答
0
string[] words = new string[5];
    foreach (string word in words) {

        Console.WriteLine("Type in a word");

        word = Console.ReadLine();

        var ordered = words.Where(w=>!String.IsNullOrEmpty(w)).OrderBy(w=>w.length)

        if (ordered.First() == word) 
            Console.Write("Shortest");
        if (ordered.Last() == word)
            Console.Write("Longest");

        // First time will display both "Shortest" and "Longest" since it's the only word.
        // You may adjust code depending on what do you want to do in case of words of same length.
        Console.ReadKey(true);
    }
}
于 2013-08-23T04:17:19.827 回答
0

正如@DStanley 和@RenniePet 指出的那样,您的原始代码并不能完全满足您的要求。我确实相信您想循环遍历字符串数组的成员并用控制台输入填充它们。工作代码如下所示:

    string[] word = new string[5];

        for (int i = 0; i < word.Length; i++)
        {
            Console.Write("Input text: ");
            word[i] = Console.ReadLine();
        }

        List<string> _sortedWords = word.ToList<string>();
        _sortedWords.Sort((x, y) => x.Length.CompareTo(y.Length));

        Console.WriteLine("Smaller: " + _sortedWords[0]);
        Console.WriteLine("Larget: " + _sortedWords[_sortedWords.Count-1]);

        Console.ReadLine();
于 2013-08-23T04:18:55.160 回答
0

Linq OrderBy 解决方案非常好,但不会为您提供所有结果,因为可能存在超过 1 个具有最大/最小长度的字符串。

下面的解决方案将获得最大的字符串长度并返回一个包含所有匹配项的新数组,以防万一您有超过 1 个具有相同的最大或最小长度。

最长长度

// Getting the max length strings from the array
int max = word.Max(s =>  s.Length);

// Selecting the values where the length is equal to the max value above
string[] arrayMaxLength = word.Where(s => s.Length == max).ToArray();

最小长度

// Getting the min length strings from the array
int min = word.Min(s => s.Length);

// Selecting the values where the length is equal to the min value above
string[] arrayMinLength = word.Where(s => s.Length == min).ToArray();
于 2021-09-05T02:51:54.047 回答