Compare length of two strings: Difference between revisions
m
no edit summary
m (→{{header|Wren}}: Changed to Wren S/H) |
mNo edit summary |
||
(5 intermediate revisions by 3 users not shown) | |||
Line 1,118:
</pre>
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|10+}}
<syntaxhighlight lang="csharp">
void WriteSorted(string[] strings)
{
var sorted = strings.OrderByDescending(x => x.Length);
foreach(var s in sorted) Console.WriteLine($"{s.Length}: {s}");
}
WriteSorted(new string[] { "abcd", "123456789", "abcdef", "1234567" });
</syntaxhighlight>
{{output}}
<pre>
9: 123456789
7: 1234567
6: abcdef
4: abcd
</pre>
Line 1,305 ⟶ 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}}==
Line 2,753 ⟶ 2,729:
"e" has length 1 and is the shortest
</pre>
=={{header|Scala}}==
{{trans|Java}}
<syntaxhighlight lang="Scala">
object Example extends App {
val strings = Array("abcd", "123456789", "abcdef", "1234567")
compareAndReportStringsLength(strings)
def compareAndReportStringsLength(strings: Array[String]): Unit = {
if (strings.nonEmpty) {
val Q = '"'
val hasLength = " has length "
val predicateMax = " and is the longest string"
val predicateMin = " and is the shortest string"
val predicateAve = " and is neither the longest nor the shortest string"
val sortedStrings = strings.sortBy(-_.length)
val maxLength = sortedStrings.head.length
val minLength = sortedStrings.last.length
sortedStrings.foreach { str =>
val length = str.length
val predicate = length match {
case `maxLength` => predicateMax
case `minLength` => predicateMin
case _ => predicateAve
}
println(s"$Q$str$Q$hasLength$length$predicate")
}
}
}
}
</syntaxhighlight>
{{out}}
<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|Transd}}==
|