Compare length of two strings: Difference between revisions
Add Kotlin
(added Emacs Lisp code to order strings by length) |
(Add Kotlin) |
||
(4 intermediate revisions by 3 users not shown) | |||
Line 1,269:
<syntaxhighlight lang="lisp">
(defun sort-list-by-string-length (list-of-strings)
"
(sort list-of-strings 'longer-string)) ;
(defun longer-string (string-1 string-2)
Line 1,894:
"shorter😀" has length (codepoints) 8 and utf8 byte length 11.
"longer" has length (codepoints) 6 and utf8 byte length 6.
</pre>
fun main() {
printTwoStrings("a short string", "a fairly long string")
}
fun printTwoStrings(a: String, b: String) {
val (shorter, longer) = if (a.length < b.length) Pair(a, b) else Pair(b, a)
println("%3d: %s".format(longer.length, longer))
println("%3d: %s".format(shorter.length, shorter))
}
fun printStringsInDescendingLengthOrder(strings: Collection<String>) {
strings.sortedByDescending(String::length).forEach {
println("%3d: %s".format(it.length, it))
}
{{out}}
<pre>
20: a fairly long string
14: a short string
9: 123456789
7: 1234567
6: abcdef
4: abcd
</pre>
Line 2,144 ⟶ 2,173:
6 Pascal
6 Foobar</pre>
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="pascal">
begin
var (s1,s2) := ('Bye','Hello');
if s1.Length < s2.Length then
Swap(s1,s2);
Println(s1,s1.Length);
Println(s2,s2.Length);
Println;
var strArr := |'wolf','cat','crocodile','tiger'|;
strArr.OrderByDescending(s -> s.Length).PrintLines(s -> $'{s,9} - {s.Length}');
end.
</syntaxhighlight>
{{out}}
<pre>
Hello 5
Bye 3
crocodile - 9
tiger - 5
wolf - 4
cat - 3
</pre>
=={{header|Perl}}==
Line 2,771 ⟶ 2,824:
</pre>
=={{header|Swift}}==
Swift provides a simple ''count'' property to find how many syntactic characters are in any given String. When counting bytes Swift supports Unicode codepoints.
In this example we use the ''sorted'' and ''forEach'' methods from the Sequence protocol to first sort our list into a new Array and then print each item in order. String interpolation is used to print the details of each item.
▲=={{header|Transd}}==
▲<syntaxhighlight lang="Scheme">#lang transd
Here we use anonymous argument names with the ''sorted'' closure and a named argument with the ''forEach'' to illustrate how to use either style.
<syntaxhighlight lang="Swift">
▲ v: ["abcd","123456789","abcdef","1234567"],
let list = ["abcd", "abcd🤦♂️", "123456789", "abcdef", "1234567"]
list.sorted { $0.count > $1.count }.forEach { string in
}
</syntaxhighlight>
▲ )
▲}</syntaxhighlight>
{{out}}
<pre>
abcd🤦♂️ has 5 characters
abcd has 4 characters
</pre>
|