Compare length of two strings: Difference between revisions

no edit summary
No edit summary
Line 161:
return EXIT_SUCCESS;
}</lang>
 
{{output}}
<pre>"123456789" has length 9 and is the longest string
"1234567" has length 7 and is neither the longest nor the shortest string
"abcdef" has length 6 and is neither the longest nor the shortest string
"abcd" has length 4 and is the shortest string
</pre>
=={{header|C#}}==
<lang csharp>using System;
using System.Collections.Generic;
 
namespace example
{
class Program
{
static void Main(string[] args)
{
var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(strings);
}
 
private static void compareAndReportStringsLength(string[] strings)
{
if (strings.Length > 0)
{
char Q = '"';
string has_length = " has length ";
string predicate_max = " and is the longest string";
string predicate_min = " and is the shortest string";
string predicate_ave = " and is neither the longest nor the shortest string";
string predicate;
 
(int, int)[] li = new (int, int)[strings.Length];
for (int i = 0; i < strings.Length; i++)
li[i] = (strings[i].Length, i);
Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);
int max_length = li[0].Item1;
int min_length = li[strings.Length - 1].Item1;
 
for (int i = 0; i < strings.Length; i++)
{
int length = li[i].Item1;
string str = strings[li[i].Item2];
if (length == max_length)
predicate = predicate_max;
else if (length == min_length)
predicate = predicate_min;
else
predicate = predicate_ave;
Console.WriteLine(Q + str + Q + has_length + length + predicate);
}
}
}
 
}
}
</lang>
 
{{output}}