Compare length of two strings: Difference between revisions

m
no edit summary
mNo edit summary
(3 intermediate revisions by 2 users not shown)
Line 1,118:
</pre>
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|10+}}
<syntaxhighlight lang="csharp">
void WriteSorted(string[] strings)
using System;
using System.Collections.Generic;
 
namespace example
{
var sorted = strings.OrderByDescending(x => x.Length);
class Program
foreach(var s in sorted) Console.WriteLine($"{s.Length}: {s}");
{
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 hasLength = " has length ";
string predicateMax = " and is the longest string";
string predicateMin = " and is the shortest string";
string predicateAve = " 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 maxLength = li[0].Item1;
int minLength = 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 == maxLength)
predicate = predicateMax;
else if (length == minLength)
predicate = predicateMin;
else
predicate = predicateAve;
Console.WriteLine(Q + str + Q + hasLength + length + predicate);
}
}
}
}
}
var strings = WriteSorted(new string[] { "abcd", "123456789", "abcdef", "1234567" });
</syntaxhighlight>
 
{{output}}
<pre>
9: 123456789
"123456789" has length 9 and is the longest string
7: 1234567
"1234567" has length 7 and is neither the longest nor the shortest string
6: abcdef
"abcdef" has length 6 and is neither the longest nor the shortest string
4: abcd
"abcd" has length 4 and is the shortest string
</pre>
 
Line 1,306 ⟶ 1,265:
scmp "Rosetta" "Code"
</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">
(defun sort-list-by-string-length (list-of-strings)
"Order LIST-OF-STRINGS from longest to shortest."
(sort list-of-strings 'longer-string)) ; sort by "longer-string" function below
 
(defun longer-string (string-1 string-2)
"Test if STRING-1 is longer than STRING-2."
(> (length string-1) (length string-2))) ; is STRING-1 longer than STRING-2?
</syntaxhighlight>
{{out}}
(sort-list-by-string-length '("abcd" "123456789" "abcdef" "1234567"))
<pre>
("123456789" "1234567" "abcdef" "abcd")
</pre>
 
=={{header|EMal}}==
27

edits