Compare length of two strings: Difference between revisions

From Rosetta Code
Content added Content deleted
(PL/I code added)
m (syntax highlighting fixup automation)
Line 18: Line 18:
=={{header|Ada}}==
=={{header|Ada}}==


<lang ada>with ada.command_line, ada.containers.indefinite_vectors, ada.text_io;
<syntaxhighlight lang="ada">with ada.command_line, ada.containers.indefinite_vectors, ada.text_io;
procedure compare_lengths is
procedure compare_lengths is
package string_vector is new ada.containers.indefinite_vectors
package string_vector is new ada.containers.indefinite_vectors
Line 39: Line 39:
end loop;
end loop;
end compare_lengths;
end compare_lengths;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
./compare_lengths Like sands through the hourglass these are the days of our lives
./compare_lengths Like sands through the hourglass these are the days of our lives
Line 60: Line 60:
Algol 68 does not have an in-built "LENGTH" operator, it does have operators LWB and UPB which return the lower bound and upper bound of an array and as strings are arrays of characters, LENGTH can easily be constructed from these.<br>
Algol 68 does not have an in-built "LENGTH" operator, it does have operators LWB and UPB which return the lower bound and upper bound of an array and as strings are arrays of characters, LENGTH can easily be constructed from these.<br>
In most Algol 68 implementations such as Algol 68G and Rutgers Algol 68, the CHAR type is an 8-bit byte.
In most Algol 68 implementations such as Algol 68G and Rutgers Algol 68, the CHAR type is an 8-bit byte.
<lang algol68>BEGIN # compare string lengths #
<syntaxhighlight lang="algol68">BEGIN # compare string lengths #
# returns the length of s using the builtin UPB and LWB operators #
# returns the length of s using the builtin UPB and LWB operators #
OP LENGTH = ( STRING s )INT: ( UPB s + 1 ) - LWB s;
OP LENGTH = ( STRING s )INT: ( UPB s + 1 ) - LWB s;
Line 71: Line 71:
print string( not shorter );
print string( not shorter );
IF LENGTH shorter <= LENGTH not shorter THEN print string( shorter ) FI
IF LENGTH shorter <= LENGTH not shorter THEN print string( shorter ) FI
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 80: Line 80:
=={{header|APL}}==
=={{header|APL}}==
For a good intro to APL, see [https://archive.org/details/apl-2-at-a-glance-brown-pakin-polivka/mode/2up APL2 At A Glance]
For a good intro to APL, see [https://archive.org/details/apl-2-at-a-glance-brown-pakin-polivka/mode/2up APL2 At A Glance]
<syntaxhighlight lang="apl">
<lang APL>
sv ← 'defg' 'hijklm' 'abc' 'abcd'
sv ← 'defg' 'hijklm' 'abc' 'abcd'
⍉(⍴¨sv[⍒sv]),[0.5]sv[⍒sv]
⍉(⍴¨sv[⍒sv]),[0.5]sv[⍒sv]
Line 87: Line 87:
4 abcd
4 abcd
3 abc
3 abc
</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>sortByLength: function [strs][
<syntaxhighlight lang="rebol">sortByLength: function [strs][
map sort.descending.by:'v
map sort.descending.by:'v
map strs 'str -> #[s: str, v: size str]
map strs 'str -> #[s: str, v: size str]
Line 112: Line 112:
]
]


print ["sorted strings (by length):" sortByLength ["abcd" "123456789" "abcdef" "1234567"]]</lang>
print ["sorted strings (by length):" sortByLength ["abcd" "123456789" "abcdef" "1234567"]]</syntaxhighlight>


{{out}}
{{out}}
Line 120: Line 120:


=={{header|Asymptote}}==
=={{header|Asymptote}}==
<lang Asymptote>string A, B, t = '\t';
<syntaxhighlight lang="asymptote">string A, B, t = '\t';


void comp(string A, string B) {
void comp(string A, string B) {
Line 132: Line 132:
}
}


comp("abcd", "123456789");</lang>
comp("abcd", "123456789");</syntaxhighlight>
{{out}}
{{out}}
<pre>123456789 9
<pre>123456789 9
Line 138: Line 138:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>list := ["abcd","123456789","abcdef","1234567"]
<syntaxhighlight lang="autohotkey">list := ["abcd","123456789","abcdef","1234567"]


sorted := []
sorted := []
Line 156: Line 156:
}
}
}
}
MsgBox % result</lang>
MsgBox % result</syntaxhighlight>
{{out}}
{{out}}
<pre>"123456789" has length 9 and is the longest string.
<pre>"123456789" has length 9 and is the longest string.
Line 164: Line 164:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f COMPARE_LENGTH_OF_TWO_STRINGS.AWK
# syntax: GAWK -f COMPARE_LENGTH_OF_TWO_STRINGS.AWK
BEGIN {
BEGIN {
Line 185: Line 185:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 204: Line 204:
BQN's grade functions(similar to APL) produces the indices to sort an array. We grade the lengths, then use those to arrage the strings correctly.
BQN's grade functions(similar to APL) produces the indices to sort an array. We grade the lengths, then use those to arrage the strings correctly.


<lang bqn>Compare ← >·(⍒⊑¨)⊸⊏≠⊸⋈¨
<syntaxhighlight lang="bqn">Compare ← >·(⍒⊑¨)⊸⊏≠⊸⋈¨


•Show Compare ⟨"hello", "person"⟩
•Show Compare ⟨"hello", "person"⟩
•Show Compare ⟨"abcd", "123456789", "abcdef", "1234567"⟩</lang>
•Show Compare ⟨"abcd", "123456789", "abcdef", "1234567"⟩</syntaxhighlight>
<lang>┌─
<syntaxhighlight lang="text">┌─
╵ 6 "person"
╵ 6 "person"
5 "hello"
5 "hello"
Line 217: Line 217:
6 "abcdef"
6 "abcdef"
4 "abcd"
4 "abcd"
┘</lang>
┘</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
{{Works with|C11}}
{{Works with|C11}}
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 283: Line 283:


return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 293: Line 293:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <algorithm>
#include <algorithm>
#include <string>
#include <string>
Line 342: Line 342:


return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 351: Line 351:
</pre>
</pre>
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;


Line 399: Line 399:
}
}
}
}
</syntaxhighlight>
</lang>


{{output}}
{{output}}
Line 409: Line 409:


=={{header|CFEngine}}==
=={{header|CFEngine}}==
<lang cfengine3>
<syntaxhighlight lang="cfengine3">
bundle agent __main__
bundle agent __main__
{
{
Line 424: Line 424:
"'$(sorted[$(sort_idx)])' is $(sort_idx) characters in length.";
"'$(sorted[$(sort_idx)])' is $(sort_idx) characters in length.";
}
}
</syntaxhighlight>
</lang>


{{output}}
{{output}}
Line 460: Line 460:
{{works with|Commodore BASIC|2.0}}
{{works with|Commodore BASIC|2.0}}
{{works with|Commodore BASIC|3.5}}
{{works with|Commodore BASIC|3.5}}
<lang gwbasic>0 REM ROSETTACODE.ORG
<syntaxhighlight lang="gwbasic">0 REM ROSETTACODE.ORG
1 REM COMPARE LENGTH OF TWO STRINGS
1 REM COMPARE LENGTH OF TWO STRINGS
2 REM GIVEN TWO STRINGS OF DIFFERENT
2 REM GIVEN TWO STRINGS OF DIFFERENT
Line 515: Line 515:
1080 DATA "I LIKE TEA"
1080 DATA "I LIKE TEA"
1090 DATA "WE SEE THEM EVERY WEEK"
1090 DATA "WE SEE THEM EVERY WEEK"
1100 DATA "$$$"</lang>
1100 DATA "$$$"</syntaxhighlight>


{{out}}
{{out}}
Line 539: Line 539:


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang basic256>subroutine comp(A$, B$)
<syntaxhighlight lang="basic256">subroutine comp(A$, B$)
if length(A$) >= length(B$) then
if length(A$) >= length(B$) then
print A$, length(A$)
print A$, length(A$)
Line 549: Line 549:
end subroutine
end subroutine


call comp("abcd", "123456789")</lang>
call comp("abcd", "123456789")</syntaxhighlight>


==={{header|PureBasic}}===
==={{header|PureBasic}}===
<lang PureBasic>Procedure comp(A.s, B.s)
<syntaxhighlight lang="purebasic">Procedure comp(A.s, B.s)
If Len(A) >= Len(B)
If Len(A) >= Len(B)
PrintN(A + #TAB$ + Str(Len(A)))
PrintN(A + #TAB$ + Str(Len(A)))
Line 565: Line 565:
comp("abcd", "123456789")
comp("abcd", "123456789")
Input()
Input()
CloseConsole()</lang>
CloseConsole()</syntaxhighlight>


==={{header|QBasic}}===
==={{header|QBasic}}===
Line 571: Line 571:
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
{{works with|True BASIC}}
{{works with|True BASIC}}
<lang QBasic>SUB comp(A$, B$)
<syntaxhighlight lang="qbasic">SUB comp(A$, B$)
IF LEN(A$) >= LEN(B$) THEN
IF LEN(A$) >= LEN(B$) THEN
PRINT A$, LEN(A$)
PRINT A$, LEN(A$)
Line 582: Line 582:


CALL comp("abcd", "123456789")
CALL comp("abcd", "123456789")
END</lang>
END</syntaxhighlight>


==={{header|Run BASIC}}===
==={{header|Run BASIC}}===
<lang runbasic>sub comp A$, B$
<syntaxhighlight lang="runbasic">sub comp A$, B$
if len(A$) >= len(B$) then
if len(A$) >= len(B$) then
print A$; chr$(9); len(A$)
print A$; chr$(9); len(A$)
Line 595: Line 595:
end sub
end sub


call comp "abcd", "123456789"</lang>
call comp "abcd", "123456789"</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
{{works with|QBasic}}
{{works with|QBasic}}
<lang qbasic>SUB comp(A$, B$)
<syntaxhighlight lang="qbasic">SUB comp(A$, B$)
IF LEN(A$) >= LEN(B$) THEN
IF LEN(A$) >= LEN(B$) THEN
PRINT A$, LEN(A$)
PRINT A$, LEN(A$)
Line 610: Line 610:


CALL comp("abcd", "123456789")
CALL comp("abcd", "123456789")
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>Igual que la entrada de FreeBASIC.
<pre>Igual que la entrada de FreeBASIC.
Line 616: Line 616:


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang yabasic>sub comp(A$, B$)
<syntaxhighlight lang="yabasic">sub comp(A$, B$)
if len(A$) >= len(B$) then
if len(A$) >= len(B$) then
print A$, chr$(9), len(A$)
print A$, chr$(9), len(A$)
Line 626: Line 626:
end sub
end sub


comp("abcd", "123456789")</lang>
comp("abcd", "123456789")</syntaxhighlight>


==={{header|FreeBASIC}}===
==={{header|FreeBASIC}}===
<lang freebasic>sub comp( A as string, B as string )
<syntaxhighlight lang="freebasic">sub comp( A as string, B as string )
if len(A)>=len(B) then
if len(A)>=len(B) then
print A, len(A)
print A, len(A)
Line 639: Line 639:
end sub
end sub


comp( "abcd", "123456789" )</lang>
comp( "abcd", "123456789" )</syntaxhighlight>
{{out}}<pre>123456789 9
{{out}}<pre>123456789 9
abcd 4</pre>
abcd 4</pre>
Line 647: Line 647:
remain self-contained, created (a very inefficient) sort_int()
remain self-contained, created (a very inefficient) sort_int()
procedure.
procedure.
<lang fortran>
<syntaxhighlight lang="fortran">
program demo_sort_indexed
program demo_sort_indexed
implicit none
implicit none
Line 673: Line 673:


end program demo_sort_indexed
end program demo_sort_indexed
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 697: Line 697:


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang futurebasic>local fn MyArraySortFunction( obj1 as CFTypeRef, obj2 as CFTypeRef, context as ptr ) as NSComparisonResult
<syntaxhighlight lang="futurebasic">local fn MyArraySortFunction( obj1 as CFTypeRef, obj2 as CFTypeRef, context as ptr ) as NSComparisonResult
NSComparisonResult result = NSOrderedDescending
NSComparisonResult result = NSOrderedDescending
if len(obj1) >= len(obj2) then result = NSOrderedAscending
if len(obj1) >= len(obj2) then result = NSOrderedAscending
Line 727: Line 727:
fn DoIt
fn DoIt


HandleEvents</lang>
HandleEvents</syntaxhighlight>


Output:
Output:
Line 739: Line 739:
=={{header|Go}}==
=={{header|Go}}==
{{works with|Go|1.8+}}
{{works with|Go|1.8+}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 769: Line 769:
fmt.Printf("%d: %s\n", len(s), s)
fmt.Printf("%d: %s\n", len(s), s)
}
}
}</lang>
}</syntaxhighlight>
sort.SliceStable takes comparison function "less" as a second argument. As long as the function satisfies Interface type's Less method you can use it for comparison, see [https://pkg.go.dev/sort?utm_source=gopls#SliceStable SliceStable]
sort.SliceStable takes comparison function "less" as a second argument. As long as the function satisfies Interface type's Less method you can use it for comparison, see [https://pkg.go.dev/sort?utm_source=gopls#SliceStable SliceStable]
<lang go>comparisonFunction := func(i, j int) bool {
<syntaxhighlight lang="go">comparisonFunction := func(i, j int) bool {
return len(strings[i]) > len(strings[j])
return len(strings[i]) > len(strings[j])
}
}


sort.SliceStable(strings, comparisonFunction)</lang>
sort.SliceStable(strings, comparisonFunction)</syntaxhighlight>
{{output}}
{{output}}
.\main.exe
.\main.exe
Line 794: Line 794:
=={{header|Harbour}}==
=={{header|Harbour}}==
We can, easily, realize this task with Harbour, utilizing its strong array-handling set of functions.
We can, easily, realize this task with Harbour, utilizing its strong array-handling set of functions.
<lang visualfoxpro>
<syntaxhighlight lang="visualfoxpro">


PROCEDURE Main()
PROCEDURE Main()
Line 820: Line 820:
hb_strFormat( "(length = %d chars)", Len(e) ) ) } )
hb_strFormat( "(length = %d chars)", Len(e) ) ) } )
RETURN NIL
RETURN NIL
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 845: Line 845:
=={{header|Haskell}}==
=={{header|Haskell}}==
Using native String type:
Using native String type:
<lang haskell>task s1 s2 = do
<syntaxhighlight lang="haskell">task s1 s2 = do
let strs = if length s1 > length s2 then [s1, s2] else [s2, s1]
let strs = if length s1 > length s2 then [s1, s2] else [s2, s1]
mapM_ (\s -> putStrLn $ show (length s) ++ "\t" ++ show s) strs</lang>
mapM_ (\s -> putStrLn $ show (length s) ++ "\t" ++ show s) strs</syntaxhighlight>


<pre>λ> task "short string" "longer string"
<pre>λ> task "short string" "longer string"
Line 860: Line 860:


or more practically useful Text:
or more practically useful Text:
<lang haskell>import qualified Data.Text as T
<syntaxhighlight lang="haskell">import qualified Data.Text as T


taskT s1 s2 = do
taskT s1 s2 = do
let strs = if T.length s1 > T.length s2 then [s1, s2] else [s2, s1]
let strs = if T.length s1 > T.length s2 then [s1, s2] else [s2, s1]
mapM_ (\s -> putStrLn $ show (T.length s) ++ "\t" ++ show s) strs</lang>
mapM_ (\s -> putStrLn $ show (T.length s) ++ "\t" ++ show s) strs</syntaxhighlight>


<pre>λ> :set -XOverloadedStrings
<pre>λ> :set -XOverloadedStrings
Line 938: Line 938:
{{Works with| Java | 11 }}
{{Works with| Java | 11 }}
{{Works with| Java | 17 }}
{{Works with| Java | 17 }}
<lang Java>package stringlensort;
<syntaxhighlight lang="java">package stringlensort;


import java.io.PrintStream;
import java.io.PrintStream;
Line 991: Line 991:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 1,001: Line 1,001:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
JavaScript (ECMA Script) file stringlensort.js.
JavaScript (ECMA Script) file stringlensort.js.
<lang javascript>/**
<syntaxhighlight lang="javascript">/**
* Compare and report strings lengths.
* Compare and report strings lengths.
*
*
Line 1,068: Line 1,068:


document.getElementById("input").value = "abcd\n123456789\nabcdef\n1234567";
document.getElementById("input").value = "abcd\n123456789\nabcdef\n1234567";
compareStringsLength(input, output);</lang>
compareStringsLength(input, output);</syntaxhighlight>
HTML file (with embeded CSS) to run the script.
HTML file (with embeded CSS) to run the script.
<lang HTML><html>
<syntaxhighlight lang="html"><html>


<head>
<head>
Line 1,116: Line 1,116:
</body>
</body>


</html></lang>
</html></syntaxhighlight>
{{Output}}
{{Output}}
<pre>"123456789" has length 9 and is the longest string
<pre>"123456789" has length 9 and is the longest string
Line 1,130: Line 1,130:
The Char data type in Julia is a 32-bit, potentially Unicode data type, so that if we enumerate a String
The Char data type in Julia is a 32-bit, potentially Unicode data type, so that if we enumerate a String
as a Char array, we get a series of 32-bit characters:
as a Char array, we get a series of 32-bit characters:
<lang julia>s = "niño"
<syntaxhighlight lang="julia">s = "niño"
println("Position Char Bytes\n==============================")
println("Position Char Bytes\n==============================")
for (i, c) in enumerate(s)
for (i, c) in enumerate(s)
println("$i $c $(sizeof(c))")
println("$i $c $(sizeof(c))")
end
end
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
Position Char Bytes
Position Char Bytes
Line 1,150: Line 1,150:
one byte, an error is thrown for bad indexing. This can be demonstrated by casting
one byte, an error is thrown for bad indexing. This can be demonstrated by casting
the above string to codeunits:
the above string to codeunits:
<lang julia>println("Position Codeunit Bytes\n==============================")
<syntaxhighlight lang="julia">println("Position Codeunit Bytes\n==============================")
for (i, c) in enumerate(codeunits(s))
for (i, c) in enumerate(codeunits(s))
println("$i $(string(c, base=16)) $(sizeof(c))")
println("$i $(string(c, base=16)) $(sizeof(c))")
end
end
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
Position Codeunit Bytes
Position Codeunit Bytes
Line 1,168: Line 1,168:
of "niño" as codeunits (ie, 8 bit bytes) is 5. Indexing into the 4th position
of "niño" as codeunits (ie, 8 bit bytes) is 5. Indexing into the 4th position
results in an error:
results in an error:
<lang julia>
<syntaxhighlight lang="julia">
julia> s[4]
julia> s[4]
ERROR: StringIndexError: invalid index [4], valid nearby indices [3]=>'ñ', [5]=>'o'
ERROR: StringIndexError: invalid index [4], valid nearby indices [3]=>'ñ', [5]=>'o'
</syntaxhighlight>
</lang>


So, whether a string is longer or shorter depends on the encoding, as below:
So, whether a string is longer or shorter depends on the encoding, as below:
<lang julia>length("ñññ") < length("nnnn") # true, and the usual meaning of length of a String
<syntaxhighlight lang="julia">length("ñññ") < length("nnnn") # true, and the usual meaning of length of a String


length(codeunits("ñññ")) > length(codeunits("nnnn")) # true as well
length(codeunits("ñññ")) > length(codeunits("nnnn")) # true as well
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
{{works with|jq}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
'''Works with gojq, the Go implementation of jq'''
<syntaxhighlight lang="jq">
<lang jq>
def s1: "longer";
def s1: "longer";
def s2: "shorter😀";
def s2: "shorter😀";
Line 1,191: Line 1,191:
| "\"\(.)\" has length (codepoints) \(length) and utf8 byte length \(utf8bytelength)."
| "\"\(.)\" has length (codepoints) \(length) and utf8 byte length \(utf8bytelength)."


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,202: Line 1,202:


Using these primitives we define 2 helper functions, [L.new, L.disp], to build and display a list according to a chosen format.
Using these primitives we define 2 helper functions, [L.new, L.disp], to build and display a list according to a chosen format.
<syntaxhighlight lang="scheme">
<lang Scheme>
{def L.new
{def L.new
{lambda {:s}
{lambda {:s}
Line 1,217: Line 1,217:
{L.disp {P.right :l}}}}}
{L.disp {P.right :l}}}}}
-> L.disp
-> L.disp
</syntaxhighlight>
</lang>


For instance
For instance


<syntaxhighlight lang="scheme">
<lang Scheme>
{def B {L.new abcd 123456789 abcdef 1234567}}
{def B {L.new abcd 123456789 abcdef 1234567}}
-> B
-> B
Line 1,231: Line 1,231:
6 : abcdef
6 : abcdef
7 : 1234567
7 : 1234567
</syntaxhighlight>
</lang>


Then we define the L.sort function waiting for a predicate function and a list.
Then we define the L.sort function waiting for a predicate function and a list.


<syntaxhighlight lang="scheme">
<lang Scheme>
{def L.sort
{def L.sort
{lambda {:filter :l}
{lambda {:filter :l}
Line 1,253: Line 1,253:
{L.insert :x :filter {P.right :l}}}}}}}
{L.insert :x :filter {P.right :l}}}}}}}
-> L.insert
-> L.insert
</syntaxhighlight>
</lang>


Using the following predicate function (which could be anonymous) testing the length of 2 words
Using the following predicate function (which could be anonymous) testing the length of 2 words


<syntaxhighlight lang="scheme">
<lang Scheme>
{def filter
{def filter
{lambda {:a :b}
{lambda {:a :b}
{> {W.length :a} {W.length :b}}}}
{> {W.length :a} {W.length :b}}}}
-> filter
-> filter
</syntaxhighlight>
</lang>


we display the B list sorted according to the length of its elements.
we display the B list sorted according to the length of its elements.


<syntaxhighlight lang="scheme">
<lang Scheme>
{L.disp {L.sort filter {B}}}
{L.disp {L.sort filter {B}}}
->
->
Line 1,273: Line 1,273:
6 : abcdef
6 : abcdef
4 : abcd
4 : abcd
</syntaxhighlight>
</lang>


Note that in lambdatalk words (and numbers) don't need to be quoted.
Note that in lambdatalk words (and numbers) don't need to be quoted.


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function test(list)
<syntaxhighlight lang="lua">function test(list)
table.sort(list, function(a,b) return #a > #b end)
table.sort(list, function(a,b) return #a > #b end)
for _,s in ipairs(list) do print(#s, s) end
for _,s in ipairs(list) do print(#s, s) end
end
end
test{"abcd", "123456789", "abcdef", "1234567"}</lang>
test{"abcd", "123456789", "abcdef", "1234567"}</syntaxhighlight>
{{out}}
{{out}}
<pre>9 123456789
<pre>9 123456789
Line 1,290: Line 1,290:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>list = {"abcd", "123456789", "abcdef", "1234567"};
<syntaxhighlight lang="mathematica">list = {"abcd", "123456789", "abcdef", "1234567"};
Reverse@SortBy[list, StringLength] // TableForm</lang>
Reverse@SortBy[list, StringLength] // TableForm</syntaxhighlight>


{{out}}<pre>
{{out}}<pre>
Line 1,306: Line 1,306:
If we want to manage a string as a Unicode sequence of code points, we have to use the module <code>unicode</code>. We can convert a string in a sequence of runes, each rune being a unicode UTF-32 value. The length of this sequence is the number of code points.
If we want to manage a string as a Unicode sequence of code points, we have to use the module <code>unicode</code>. We can convert a string in a sequence of runes, each rune being a unicode UTF-32 value. The length of this sequence is the number of code points.


<lang Nim>import strformat, unicode
<syntaxhighlight lang="nim">import strformat, unicode


const
const
Line 1,313: Line 1,313:


echo &"“{S2}”, byte length = {S2.len}, code points: {S2.toRunes.len}"
echo &"“{S2}”, byte length = {S2.len}, code points: {S2.toRunes.len}"
echo &"“{S1}”, byte length = {S1.len}, code points: {S1.toRunes.len}"</lang>
echo &"“{S1}”, byte length = {S1.len}, code points: {S1.toRunes.len}"</syntaxhighlight>


{{out}}
{{out}}
Line 1,321: Line 1,321:
=={{header|Pascal}}==
=={{header|Pascal}}==
{{works with|Extended Pascal}}
{{works with|Extended Pascal}}
<lang pascal>program compareLengthOfStrings(output);
<syntaxhighlight lang="pascal">program compareLengthOfStrings(output);


const
const
Line 1,383: Line 1,383:
analyzeLengths;
analyzeLengths;
printSortedByLengths
printSortedByLengths
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre> 11 RosettaCode
<pre> 11 RosettaCode
Line 1,391: Line 1,391:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl


use strict; # https://rosettacode.org/wiki/Compare_length_of_two_strings
use strict; # https://rosettacode.org/wiki/Compare_length_of_two_strings
Line 1,401: Line 1,401:
printf "length %d: %s\n", length(), $_
printf "length %d: %s\n", length(), $_
for sort { length $b <=> length $a } split;
for sort { length $b <=> length $a } split;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,418: Line 1,418:
=={{header|Phix}}==
=={{header|Phix}}==
Lengths are in bytes, for codepoints use length(utf8_to_utf32()) or similar.
Lengths are in bytes, for codepoints use length(utf8_to_utf32()) or similar.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">list</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"abcd"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"123456789"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"abcdef"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1234567"</span><span style="color: #0000FF;">},</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">list</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"abcd"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"123456789"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"abcdef"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1234567"</span><span style="color: #0000FF;">},</span>
Line 1,424: Line 1,424:
<span style="color: #000000;">tags</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">custom_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lens</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lens</span><span style="color: #0000FF;">))))</span>
<span style="color: #000000;">tags</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">custom_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lens</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lens</span><span style="color: #0000FF;">))))</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">printf</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"%s (length %d)\n"</span><span style="color: #0000FF;">},</span><span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">extract</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tags</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">extract</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lens</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tags</span><span style="color: #0000FF;">)})})</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">printf</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"%s (length %d)\n"</span><span style="color: #0000FF;">},</span><span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">extract</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tags</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">extract</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lens</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tags</span><span style="color: #0000FF;">)})})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,434: Line 1,434:


=={{header|PHP}}==
=={{header|PHP}}==
<syntaxhighlight lang="php">
<lang PHP>
<?php
<?php


Line 1,535: Line 1,535:
</body>
</body>


</html></lang>
</html></syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare (S1, S2) character (20) varying; /* 11 Aug 2022 */
declare (S1, S2) character (20) varying; /* 11 Aug 2022 */
get (S1, S2);
get (S1, S2);
Line 1,545: Line 1,545:
else
else
put (length(S2), S2);
put (length(S2), S2);
</syntaxhighlight>
</lang>


=={{header|Python}}==
=={{header|Python}}==
===Naive solution===
===Naive solution===
{{works with | Python | 3.8}}
{{works with | Python | 3.8}}
<lang Python>A = 'I am string'
<syntaxhighlight lang="python">A = 'I am string'
B = 'I am string too'
B = 'I am string too'


Line 1,561: Line 1,561:
else:
else:
print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string')
print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string')
print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')</lang>
print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 1,573: Line 1,573:
The solution below has some imperfection. When the longest strings of characters are of equal length, instead of describing them as "''one of the longest''" they are described as "''the longest''". This works similarly for the shortest strings. Also, if all strings (in this case where there is only one) have the same length it is not printed that they are the shortest strings. Of course, this could be improved.
The solution below has some imperfection. When the longest strings of characters are of equal length, instead of describing them as "''one of the longest''" they are described as "''the longest''". This works similarly for the shortest strings. Also, if all strings (in this case where there is only one) have the same length it is not printed that they are the shortest strings. Of course, this could be improved.


<syntaxhighlight lang="python">"""
<lang Python>"""
An example code for the task "Compare length of two strings" (Rosseta Code).
An example code for the task "Compare length of two strings" (Rosseta Code).


Line 1,655: Line 1,655:
compare_and_report_length(*LIST)
compare_and_report_length(*LIST)
print()
print()
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,674: Line 1,674:
=={{header|QB64}}==
=={{header|QB64}}==


<syntaxhighlight lang="qb64">
<lang QB64>
Dim Words(1 To 4) As String
Dim Words(1 To 4) As String
Dim Lengths As Integer, Index As Integer, Position As Integer, Done As String, Index2 As Integer
Dim Lengths As Integer, Index As Integer, Position As Integer, Done As String, Index2 As Integer
Line 1,696: Line 1,696:
Print Words(Position), Len(Words(Position))
Print Words(Position), Len(Words(Position))
Next Index2
Next Index2
</syntaxhighlight>
</lang>
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> $ "A short string of"
<syntaxhighlight lang="quackery"> $ "A short string of"
$ "A slightly longer string of"
$ "A slightly longer string of"
Line 1,717: Line 1,717:
sortwith [ size dip size < ]
sortwith [ size dip size < ]
witheach [ echo$ cr ] </lang>
witheach [ echo$ cr ] </syntaxhighlight>


{{out}}
{{out}}
Line 1,739: Line 1,739:
In the modern world, string "length" is pretty much a useless measurement, especially in the absence of a specified encoding; hence Raku not even having an operator: "length" for strings.
In the modern world, string "length" is pretty much a useless measurement, especially in the absence of a specified encoding; hence Raku not even having an operator: "length" for strings.


<lang perl6>say 'Strings (👨‍👩‍👧‍👦, 🤔🇺🇸, BOGUS!) sorted: "longest" first:';
<syntaxhighlight lang="raku" line>say 'Strings (👨‍👩‍👧‍👦, 🤔🇺🇸, BOGUS!) sorted: "longest" first:';
say "$_: characters:{.chars}, Unicode code points:{.codes}, UTF-8 bytes:{.encode('UTF8').bytes}, UTF-16 bytes:{.encode('UTF16').bytes}" for <👨‍👩‍👧‍👦 BOGUS! 🤔🇺🇸>.sort: -*.chars;</lang>
say "$_: characters:{.chars}, Unicode code points:{.codes}, UTF-8 bytes:{.encode('UTF8').bytes}, UTF-16 bytes:{.encode('UTF16').bytes}" for <👨‍👩‍👧‍👦 BOGUS! 🤔🇺🇸>.sort: -*.chars;</syntaxhighlight>
{{out}}
{{out}}
<pre>Strings (👨‍👩‍👧‍👦, 🤔🇺🇸, BOGUS!) sorted: "longest" first:
<pre>Strings (👨‍👩‍👧‍👦, 🤔🇺🇸, BOGUS!) sorted: "longest" first:
Line 1,748: Line 1,748:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/* REXX */
<syntaxhighlight lang="rexx">/* REXX */
list = '"abcd","123456789","abcdef","1234567"'
list = '"abcd","123456789","abcdef","1234567"'
Do i=1 By 1 While list>''
Do i=1 By 1 While list>''
Line 1,772: Line 1,772:
o:
o:
Say length(arg(1)) arg(1)
Say length(arg(1)) arg(1)
Return</lang>
Return</syntaxhighlight>
{{out}}
{{out}}
<pre>9 123456789
<pre>9 123456789
Line 1,781: Line 1,781:
=={{header|Ring}}==
=={{header|Ring}}==
===Two strings===
===Two strings===
<lang ring>
<syntaxhighlight lang="ring">
see "working..." + nl
see "working..." + nl


Line 1,796: Line 1,796:
see "" + first + " len = " + len(first) + nl + second + " len = " + len(second) + nl
see "" + first + " len = " + len(first) + nl + second + " len = " + len(second) + nl
see "done..." + nl
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,806: Line 1,806:
</pre>
</pre>
===More than two strings===
===More than two strings===
<lang ring>
<syntaxhighlight lang="ring">
see "working..." + nl
see "working..." + nl


Line 1,824: Line 1,824:
next
next
see "done..." + nl
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,837: Line 1,837:


=={{header|Ruby}}==
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
<lang Ruby>
a, b = "Given two strings", "of different length"
a, b = "Given two strings", "of different length"
[a,b].sort_by{|s| - s.size }.each{|s| puts s + " (size: #{s.size})"}
[a,b].sort_by{|s| - s.size }.each{|s| puts s + " (size: #{s.size})"}
Line 1,843: Line 1,843:
list = ["abcd","123456789","abcdef","1234567"]
list = ["abcd","123456789","abcdef","1234567"]
puts list.sort_by{|s|- s.size}
puts list.sort_by{|s|- s.size}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>of different length (size: 19)
<pre>of different length (size: 19)
Line 1,853: Line 1,853:


=={{header|Rust}}==
=={{header|Rust}}==
<syntaxhighlight lang="rust">
<lang Rust>
fn compare_and_report<T: ToString>(string1: T, string2: T) -> String {
fn compare_and_report<T: ToString>(string1: T, string2: T) -> String {
let strings = [string1.to_string(), string2.to_string()];
let strings = [string1.to_string(), string2.to_string()];
Line 1,871: Line 1,871:
println!("\n{}", compare_and_report("f", "gh"));
println!("\n{}", compare_and_report("f", "gh"));
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,885: Line 1,885:


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang go>// Compare lenth of two strings, in V
<syntaxhighlight lang="go">// Compare lenth of two strings, in V
// Tectonics: v run compare-length-of-two-strings.v
// Tectonics: v run compare-length-of-two-strings.v
module main
module main
Line 1,905: Line 1,905:
println("${strs[i]}: with length ${strs[i].len}")
println("${strs[i]}: with length ${strs[i].len}")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,928: Line 1,928:


Unicode grapheme clusters, where what appears to be a single 'character' may in fact be an amalgam of several codepoints, are not directly supported by Wren but it is possible to measure the length in grapheme clusters of a string (i.e. the number of ''user perceived characters'') using the ''Graphemes.clusterCount'' method of the Wren-upc module.
Unicode grapheme clusters, where what appears to be a single 'character' may in fact be an amalgam of several codepoints, are not directly supported by Wren but it is possible to measure the length in grapheme clusters of a string (i.e. the number of ''user perceived characters'') using the ''Graphemes.clusterCount'' method of the Wren-upc module.
<lang ecmascript>import "./upc" for Graphemes
<syntaxhighlight lang="ecmascript">import "./upc" for Graphemes


var printCounts = Fn.new { |s1, s2, c1, c2|
var printCounts = Fn.new { |s1, s2, c1, c2|
Line 1,967: Line 1,967:
System.write("Sorting in descending order by length in codepoints:\n%(list) -> ")
System.write("Sorting in descending order by length in codepoints:\n%(list) -> ")
list.sort { |a, b| a.count > b.count }
list.sort { |a, b| a.count > b.count }
System.print(list)</lang>
System.print(list)</syntaxhighlight>


{{out}}
{{out}}
Line 2,000: Line 2,000:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>string 0; \use zero-terminated string convention
<syntaxhighlight lang="xpl0">string 0; \use zero-terminated string convention


func StrLen(A); \Return number of characters in an ASCIIZ string
func StrLen(A); \Return number of characters in an ASCIIZ string
Line 2,021: Line 2,021:
List(SN, 0):= 0; \truncate largest string
List(SN, 0):= 0; \truncate largest string
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 2,032: Line 2,032:


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
<lang z80>Terminator equ 0 ;null terminator
<syntaxhighlight lang="z80">Terminator equ 0 ;null terminator
PrintChar equ &BB5A ;Amstrad CPC BIOS call, prints accumulator to screen as an ASCII character.
PrintChar equ &BB5A ;Amstrad CPC BIOS call, prints accumulator to screen as an ASCII character.


Line 2,155: Line 2,155:
add a,&F0
add a,&F0
adc a,&40 ;This sequence converts a 4-bit hex digit to its ASCII equivalent.
adc a,&40 ;This sequence converts a 4-bit hex digit to its ASCII equivalent.
jp PrintChar</lang>
jp PrintChar</syntaxhighlight>


{{out}}
{{out}}

Revision as of 20:25, 26 August 2022

Task
Compare length of two strings
You are encouraged to solve this task according to the task description, using any language you may know.

Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.

You may see other such operations in the Basic Data Operations category, or:

Integer Operations
Arithmetic | Comparison

Boolean Operations
Bitwise | Logical

String Operations
Concatenation | Interpolation | Comparison | Matching

Memory Operations
Pointers & references | Addresses

Task

Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first.

Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it.

Extra credit

Given more than two strings:
list = ["abcd","123456789","abcdef","1234567"]
Show the strings in descending length order.

Other tasks related to string operations:
Metrics
Counting
Remove/replace
Anagrams/Derangements/shuffling
Find/Search/Determine
Formatting
Song lyrics/poems/Mad Libs/phrases
Tokenize
Sequences



Ada

with ada.command_line, ada.containers.indefinite_vectors, ada.text_io;
procedure compare_lengths is
   package string_vector is new ada.containers.indefinite_vectors
     (index_type => Positive, element_type => String);

   function "<" (left, right : String) return Boolean is
   begin
      return left'length > right'length;
   end "<";

   package string_vector_sorting is new string_vector.generic_sorting;
   list : string_vector.Vector;
begin
   for i in 1 .. ada.command_line.argument_count loop
      list.append (ada.command_line.argument (i));
   end loop;
   string_vector_sorting.sort (list);
   for elem of list loop
      ada.text_io.put_line (elem'length'image & ": " & elem);
   end loop;
end compare_lengths;
Output:

./compare_lengths Like sands through the hourglass these are the days of our lives

 9: hourglass
 7: through
 5: lives
 5: sands
 5: these
 4: days
 4: Like
 3: are
 3: our
 3: the
 3: the
 2: of

ALGOL 68

Algol 68 does not have an in-built "LENGTH" operator, it does have operators LWB and UPB which return the lower bound and upper bound of an array and as strings are arrays of characters, LENGTH can easily be constructed from these.
In most Algol 68 implementations such as Algol 68G and Rutgers Algol 68, the CHAR type is an 8-bit byte.

BEGIN # compare string lengths #
    # returns the length of s using the builtin UPB and LWB operators #
    OP LENGTH = ( STRING s )INT: ( UPB s + 1 ) - LWB s;
    # prints s and its length #
    PROC print string = ( STRING s )VOID:
         print( ( """", s, """ has length: ", whole( LENGTH s, 0 ), " bytes.", newline ) );
    STRING shorter     = "short";
    STRING not shorter = "longer";
    IF LENGTH shorter >  LENGTH not shorter THEN print string( shorter ) FI;
    print string( not shorter );
    IF LENGTH shorter <= LENGTH not shorter THEN print string( shorter ) FI
END
Output:
"longer" has length: 6 bytes.
"short" has length: 5 bytes.

APL

For a good intro to APL, see APL2 At A Glance

      sv  'defg' 'hijklm' 'abc' 'abcd'
      (¨sv[sv]),[0.5]sv[sv]
 6  hijklm 
 4  defg   
 4  abcd   
 3  abc

Arturo

sortByLength: function [strs][
    map sort.descending.by:'v 
        map strs 'str -> #[s: str, v: size str] 
        'z -> z\s
]

A: "I am string"
B: "I am string too"

sA: size A
sB: size B

if? sA < sB ->
    print ["string ->" A "(" sA ") is smaller than string ->" B "(" sB ")"]
else [
    if? sA > sB ->
        print ["string ->" A "(" sA ") is larger than string ->" B "(" sB ")"]
    else ->
        print ["string ->" A "(" sA ") and string ->" B "(" sB ") are of equal length"]
]

print ["sorted strings (by length):" sortByLength ["abcd" "123456789" "abcdef" "1234567"]]
Output:
string -> I am string ( 11 ) is smaller than string -> I am string too ( 15 ) 
sorted strings (by length): [123456789 1234567 abcdef abcd]

Asymptote

string A, B, t = '\t';

void comp(string A, string B) {
    if (length(A) >= length(B)) {
        write(A+t, length(A));
        write(B+t, length(B));
    } else {
        write(B+t, length(B));
        write(A+t, length(A));
    }
}

comp("abcd", "123456789");
Output:
123456789	9
abcd	4

AutoHotkey

list := ["abcd","123456789","abcdef","1234567"]

sorted := []
for i, s in list
    sorted[0-StrLen(s), s] := s
for l, obj in sorted
{
    i := A_Index
    for s, v in obj
    {
        if (i = 1)
            result .= """" s """ has length " 0-l " and is the longest string.`n"
        else if (i < sorted.Count())
            result .= """"s """ has length " 0-l " and is neither the longest nor the shortest string.`n"
        else
            result .= """"s """ has length " 0-l " and is the shorted string.`n"
    }
}
MsgBox % result
Output:
"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 shorted string.

AWK

# syntax: GAWK -f COMPARE_LENGTH_OF_TWO_STRINGS.AWK
BEGIN {
    main("abcd","123456789")
    main("longer","short")
    main("hello","world")
    exit(0)
}
function main(Sa,Sb,  La,Lb) {
    La = length(Sa)
    Lb = length(Sb)
    if (La > Lb) {
      printf("a>b\n%3d %s\n%3d %s\n\n",La,Sa,Lb,Sb)
    }
    else if (La < Lb) {
      printf("a<b\n%3d %s\n%3d %s\n\n",Lb,Sb,La,Sa)
    }
    else {
      printf("a=b\n%3d %s\n%3d %s\n\n",Lb,Sb,La,Sa)
    }
}
Output:
a<b
  9 123456789
  4 abcd

a>b
  6 longer
  5 short

a=b
  5 world
  5 hello

BQN

BQN's grade functions(similar to APL) produces the indices to sort an array. We grade the lengths, then use those to arrage the strings correctly.

Compare  >·(⍒⊑¨)⊏≠¨

•Show Compare "hello", "person"
•Show Compare "abcd", "123456789", "abcdef", "1234567"
┌─            
╵ 6 "person"  
  5 "hello"   
             ┘
┌─               
╵ 9 "123456789"  
  7 "1234567"    
  6 "abcdef"     
  4 "abcd"       
                ┘

C

Works with: C11
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cmp(const int* a, const int* b)
{
    return *b - *a; // reverse sort!
}

void compareAndReportStringsLength(const char* strings[], const int n)
{
    if (n > 0)
    {
        char* has_length = "has length";
        char* predicate_max = "and is the longest string";
        char* predicate_min = "and is the shortest string";
        char* predicate_ave = "and is neither the longest nor the shortest string";

        int* si = malloc(2 * n * sizeof(int));
        if (si != NULL)
        {
            for (int i = 0; i < n; i++)
            {
                si[2 * i] = strlen(strings[i]);
                si[2 * i + 1] = i;
            }
            qsort(si, n, 2 * sizeof(int), cmp);

            int max = si[0];
            int min = si[2 * (n - 1)];

            for (int i = 0; i < n; i++)
            {
                int length = si[2 * i];
                char* string = strings[si[2 * i + 1]];
                char* predicate;
                if (length == max)
                    predicate = predicate_max;
                else if (length == min)
                    predicate = predicate_min;
                else
                    predicate = predicate_ave;
                printf("\"%s\" %s %d %s\n",
                    string, has_length, length, predicate);
            }

            free(si);
        }
        else
        {
            fputs("unable allocate memory buffer", stderr);
        }
    }
}

int main(int argc, char* argv[])
{
    char* list[] = { "abcd", "123456789", "abcdef", "1234567" };

    compareAndReportStringsLength(list, 4);

    return EXIT_SUCCESS;
}
Output:
"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

C++

#include <iostream>
#include <algorithm>
#include <string>
#include <list>

using namespace std;

bool cmp(const string& a, const string& b)
{
    return b.length() < a.length(); // reverse sort!
}

void compareAndReportStringsLength(list<string> listOfStrings)
{
    if (!listOfStrings.empty())
    {
        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");

        list<string> ls(listOfStrings); // clone to avoid side-effects
        ls.sort(cmp);
        int max = ls.front().length();
        int min = ls.back().length();

        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)
        {
            int length = s->length();
            string* predicate;
            if (length == max)
                predicate = &predicate_max;
            else if (length == min)
                predicate = &predicate_min;
            else
                predicate = &predicate_ave;

            cout << Q << *s << Q << has_length << length << *predicate << endl;
        }
    }
}

int main(int argc, char* argv[])
{
    list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" };
    compareAndReportStringsLength(listOfStrings);

    return EXIT_SUCCESS;
}
Output:
"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

C#

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 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);
                }
            }
        }

    }
}
Output:
"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

CFEngine

bundle agent __main__
{
  vars:
      "strings" slist => { "abcd", "123456789", "abcdef", "1234567" };

      "sorted[$(with)]"
        string => "$(strings)",
        with => string_length( "$(strings)" );

      "sort_idx" slist => reverse( sort( getindices( "sorted" ), lex ) );

  reports:
      "'$(sorted[$(sort_idx)])' is $(sort_idx) characters in length.";
}
Output:
R: '123456789' is 9 characters in length.
R: '1234567' is 7 characters in length.
R: 'abcdef' is 6 characters in length.
R: 'abcd' is 4 characters in length.

BASIC

Applesoft BASIC

Printing CHR$(14) does nothing by default in Applesoft BASIC. Commodore BASIC appends spaces to numbers, but otherwise the Compare_length_of_two_strings#Commodore_BASIC code works the same in Applesoft BASIC.

Output:
*** (1) TWO STRINGS ***
LONGER STRING (13)
SHORT STRING (12)


*** (2) MORE THAN 2 STRINGS***
SHE DOESN'T STUDY GERMAN ON MONDAY (34)
EVERY CHILD LIKES AN ICE CREAM (30)
THE COURSE STARTS NEXT SUNDAY (29)
DOES SHE LIVE IN PARIS? (23)
SHE SWIMS EVERY MORNING (23)
THE EARTH IS SPHERICAL (22)
WE SEE THEM EVERY WEEK (22)
HE DOESN'T TEACH MATH (21)
CATS HATE WATER (15)
I LIKE TEA (10)

Commodore BASIC

Works with: Applesoft BASIC
Works with: Commodore BASIC version 2.0
Works with: Commodore BASIC version 3.5
0 REM ROSETTACODE.ORG
1 REM COMPARE LENGTH OF TWO STRINGS
2 REM GIVEN TWO STRINGS OF DIFFERENT 
3 REM LENGTH, DETERMINE WHICH STRING IS
4 REM LONGER OR SHORTER. 
5 REM PRINT BOTH STRINGS AND THEIR 
6 REM LENGTH, ONE ON EACH LINE. PRINT 
7 REM THE LONGER ONE FIRST.
8 REM  
9 REM ********************************
10 REM
20 REM PRINT CHR$(14): REM CHANGE TO LOWER/UPPER CASE CHAR SET
30 GOSUB 200: REM 1 - COMPARE LENGTH OF 2 STRINGS
40 GOSUB 300: REM 2- MORE THAN 2 STRINGS
50 END
200 PRINT"*** (1) TWO STRINGS ***"
210 A$ = "SHORT STRING"
220 B$ = "LONGER STRING"
230 A = LEN(A$)
240 B = LEN(B$)
250 IF A>B THEN PRINT A$;" (";A;")": PRINT B$;" (";B;")"
260 IF A<=B THEN PRINT B$;" (";B;")": PRINT A$;" (";A;")"
270 PRINT: PRINT
280 RETURN
300 PRINT"*** (2) MORE THAN 2 STRINGS***"
310 DIM C$(100)
320 N = 0
330 READ A$
340   IF A$ = "$$$" THEN 400
350   N = N+1
360   C$(N) = A$ 
370   IF N = 100 THEN 400
380   GOTO 330
390 REM SORT THE STRINGS
400 FOR J=1 TO N-1  
410   FOR I=1 TO N-J
420     IF LEN(C$(I)) < LEN(C$(I+1)) THEN A$=C$(I): C$(I)=C$(I+1): C$(I+1)=A$
430   NEXT
440 NEXT
450 REM PRINT OUT THE STRINGS
460 FOR I=1 TO N
470   PRINT C$(I);" (";LEN(C$(I));")"
480 NEXT
490 PRINT: PRINT
500 RETURN
1000 DATA "DOES SHE LIVE IN PARIS?"
1010 DATA "HE DOESN'T TEACH MATH"
1020 DATA "CATS HATE WATER"
1030 DATA "SHE DOESN'T STUDY GERMAN ON MONDAY"
1040 DATA "EVERY CHILD LIKES AN ICE CREAM"
1050 DATA "THE EARTH IS SPHERICAL"
1060 DATA "THE COURSE STARTS NEXT SUNDAY"
1070 DATA "SHE SWIMS EVERY MORNING"
1080 DATA "I LIKE TEA"
1090 DATA "WE SEE THEM EVERY WEEK"
1100 DATA "$$$"
Output:
*** (1) TWO STRINGS ***
LONGER STRING ( 13 )
SHORT STRING ( 12 )


*** (2) MORE THAN 2 STRINGS***
SHE DOESN'T STUDY GERMAN ON MONDAY ( 34
)
EVERY CHILD LIKES AN ICE CREAM ( 30 )
THE COURSE STARTS NEXT SUNDAY ( 29 )
DOES SHE LIVE IN PARIS? ( 23 )
SHE SWIMS EVERY MORNING ( 23 )
THE EARTH IS SPHERICAL ( 22 )
WE SEE THEM EVERY WEEK ( 22 )
HE DOESN'T TEACH MATH ( 21 )
CATS HATE WATER ( 15 )
I LIKE TEA ( 10 )

BASIC256

subroutine comp(A$, B$)
    if length(A$) >= length(B$) then 
        print A$, length(A$)
        print B$, length(B$)
    else
        print B$, length(B$)
        print A$, length(A$)
    end if
end subroutine

call comp("abcd", "123456789")

PureBasic

Procedure comp(A.s, B.s)
  If Len(A) >= Len(B)
    PrintN(A + #TAB$ + Str(Len(A)))
    PrintN(B + #TAB$ + Str(Len(B)))
  Else
    PrintN(B + #TAB$ + Str(Len(B)))
    PrintN(A + #TAB$ + Str(Len(A)))
  EndIf
EndProcedure

OpenConsole()
comp("abcd", "123456789")
Input()
CloseConsole()

QBasic

Works with: QBasic version 1.1
Works with: QuickBasic version 4.5
Works with: True BASIC
SUB comp(A$, B$)
    IF LEN(A$) >= LEN(B$) THEN
       PRINT A$, LEN(A$)
       PRINT B$, LEN(B$)
    ELSE
       PRINT B$, LEN(B$)
       PRINT A$, LEN(A$)
    END IF
END SUB

CALL comp("abcd", "123456789")
END

Run BASIC

sub comp A$, B$
    if len(A$) >= len(B$) then 
        print A$; chr$(9); len(A$)
        print B$; chr$(9); len(B$)
    else
        print B$; chr$(9); len(B$)
        print A$; chr$(9); len(A$)
    end if
end sub

call comp "abcd", "123456789"

True BASIC

Works with: QBasic
SUB comp(A$, B$)
    IF LEN(A$) >= LEN(B$) THEN
       PRINT A$, LEN(A$)
       PRINT B$, LEN(B$)
    ELSE
       PRINT B$, LEN(B$)
       PRINT A$, LEN(A$)
    END IF
END SUB

CALL comp("abcd", "123456789")
END
Output:
Igual que la entrada de FreeBASIC.

Yabasic

sub comp(A$, B$)
    if len(A$) >= len(B$) then 
        print A$, chr$(9), len(A$)
        print B$, chr$(9), len(B$)
    else
        print B$, chr$(9), len(B$)
        print A$, chr$(9), len(A$)
    end if
end sub

comp("abcd", "123456789")

FreeBASIC

sub comp( A as string, B as string )
    if len(A)>=len(B) then 
        print A, len(A)
        print B, len(B)
    else
        print B, len(B)
        print A, len(A)
    end if
end sub

comp( "abcd", "123456789" )
Output:
123456789      9
abcd           4

Fortran

Normally would use an external library for sorting, but to remain self-contained, created (a very inefficient) sort_int() procedure.

program demo_sort_indexed
implicit none

   call print_sorted_by_length( [character(len=20) :: "shorter","longer"] )
   call print_sorted_by_length( [character(len=20) :: "abcd","123456789","abcdef","1234567"] )
   call print_sorted_by_length( [character(len=20) :: 'the','quick','brown','fox','jumps','over','the','lazy','dog'])

contains

subroutine print_sorted_by_length(list)
character(len=*) :: list(:)
integer :: i

   list(sort_int(len_trim(list)))=list ! sort by length from small to large
   write(*,'(i9,1x,a)')(len_trim(list(i)), list(i),i=size(list),1,-1)! print from last to first
   write(*,*)

end subroutine print_sorted_by_length

function sort_int(input) result(counts) ! **very** inefficient mini index sort 
integer :: input(:), counts(size(input)), i
   counts=[(count(input(i) > input)+count(input(i) == input(:i)),i=1, size(input) )]
end function sort_int

end program demo_sort_indexed
Output:
        7 shorter             
        6 longer              

        9 123456789           
        7 1234567             
        6 abcdef              
        4 abcd                

        5 jumps               
        5 brown               
        5 quick               
        4 lazy                
        4 over                
        3 dog                 
        3 the                 
        3 fox                 
        3 the                 

FutureBasic

local fn MyArraySortFunction( obj1 as CFTypeRef, obj2 as CFTypeRef, context as ptr ) as NSComparisonResult
  NSComparisonResult result = NSOrderedDescending
  if len(obj1) >= len(obj2) then result = NSOrderedAscending
end fn = result

void local fn DoIt
  CFStringRef string1 = @"abcd", string2 = @"abcdef", s

  if len(string1) >= len(string2)
    print string1,len(string1)
    print string2,len(string2)
  else
    print string2,len(string2)
    print string1,len(string1)
  end if

  print
  text ,,,,, 85

  CFArrayRef strings = @[@"abcd",@"123456789",@"abcdef",@"1234567"]
  strings = fn ArraySortedArrayUsingFunction( strings, @fn MyArraySortFunction, NULL )
  for s in strings
    print s,len(s)
  next
end fn

window 1

fn DoIt

HandleEvents

Output:

abcdef  6
abcd    4

123456789  9
1234567    7
abcdef     6
abcd       4

Go

Works with: Go version 1.8+
package main

import (
	"fmt"
	"os"
	"sort"
)

func main() {
	// If no command-line arguments are specified when running the program, use example data
	if len(os.Args) == 1 {
		compareStrings("abcd", "123456789", "abcdef", "1234567")
	} else {
		// First argument, os.Args[0], is program name. Command-line arguments start from 1
		strings := os.Args[1:]
		compareStrings(strings...)
	}
}

// Variadic function that takes any number of string arguments for comparison
func compareStrings(strings ...string) {
	// "strings" slice is sorted in place
	// sort.SliceStable keeps strings in their original order when elements are of equal length (unlike sort.Slice)
	sort.SliceStable(strings, func(i, j int) bool {
		return len(strings[i]) > len(strings[j])
	})

	for _, s := range strings {
		fmt.Printf("%d: %s\n", len(s), s)
	}
}

sort.SliceStable takes comparison function "less" as a second argument. As long as the function satisfies Interface type's Less method you can use it for comparison, see SliceStable

comparisonFunction := func(i, j int) bool {
	return len(strings[i]) > len(strings[j])
}

sort.SliceStable(strings, comparisonFunction)
Output:

.\main.exe

9: 123456789
7: 1234567
6: abcdef
4: abcd

.\main.exe The quick brown fox jumps over the lazy dog

5: quick
5: brown
5: jumps
4: over
4: lazy
3: The
3: fox
3: the
3: dog

Harbour

We can, easily, realize this task with Harbour, utilizing its strong array-handling set of functions.

 

PROCEDURE Main()
	LOCAL s1 := "The long string"
	LOCAL s2 := "The short string"
	LOCAL a  := { s1, s2 }
	LOCAL s3

	? s3 := "Here is how you can print the longer string first using Harbour language"
	?
	? "-------------------------------------------"
	PrintTheLongerFirst( a )
	
	a := hb_ATokens( s3, " " )
	? "-------------------------------------------"
	PrintTheLongerFirst( a )
	? "-------------------------------------------"	
	RETURN

FUNCTION PrintTheLongerFirst( a )
	LOCAL n, tmp
	a := ASort( a,,, {|x,y| Len(x) > Len(y) } )
	n:= Len( a[1] )
	AEval( a, { |e| tmp := n-Len(e), Qout( e,  Space(tmp) + ;
	            hb_strFormat( "(length = %d chars)", Len(e) ) ) } )
	RETURN NIL

Output:

Here is how you can print the longer string first using Harbour language
-------------------------------------------
The short string (length = 16 chars)
The long string  (length = 15 chars)
-------------------------------------------
language (length = 8 chars)
Harbour  (length = 7 chars)
longer   (length = 6 chars)
string   (length = 6 chars)
print    (length = 5 chars)
first    (length = 5 chars)
using    (length = 5 chars)
Here     (length = 4 chars)
how      (length = 3 chars)
you      (length = 3 chars)
can      (length = 3 chars)
the      (length = 3 chars)
is       (length = 2 chars)
-------------------------------------------

Haskell

Using native String type:

task s1 s2 = do
  let strs = if length s1 > length s2 then [s1, s2] else [s2, s1]
  mapM_ (\s -> putStrLn $ show (length s) ++ "\t" ++ show s) strs
λ> task "short string" "longer string"
13	"longer string"
12	"short string"

λ> Data.List.sortOn length ["abcd","123456789","abcdef","1234567"]
["abcd","abcdef","1234567","123456789"]

Data.List.sortOn (negate . length) ["abcd","123456789","abcdef","1234567"]
["123456789","1234567","abcdef","abcd"]

or more practically useful Text:

import qualified Data.Text as T

taskT s1 s2 = do
  let strs = if T.length s1 > T.length s2 then [s1, s2] else [s2, s1]
  mapM_ (\s -> putStrLn $ show (T.length s) ++ "\t" ++ show s) strs
λ> :set -XOverloadedStrings
λ> taskT "short string" "longer string"
13	"longer string"
12	"short string"

J

   NB. solution
   NB. `Haruno-umi Hinemosu-Notari Notarikana'
   NB. Spring ocean ; Swaying gently ; All day long.

   ,/ _2 }.\ ": (;~ #)&>  <@(7&u:);._2 '春の海 ひねもすのたり のたりかな '
│3│春の海        │    
│7│ひねもすのたり│
│5│のたりかな    │  
                         

   NB.  # y  is the tally of items (penultimate dimension) in the array y
   # 323 43 5j3
3
   
   # 'literal (a string)'
18
   
   /: 'cbad'   NB. index ordering vector (grade up)
2 1 0 3
   
   ;: 'j tokenize a sentence.'
┌─┬────────┬─┬─────────┐
│j│tokenize│a│sentence.│
└─┴────────┴─┴─────────┘
   
   #S:0 ;: 'j tokenize a sentence.'  NB. length of leaves (lowest box level)
1 8 1 9
  
   A=: '1234567 abcd 123456789 abcdef'  NB. global assignment

   (\: #S:0) ;: A  NB. order by grade down
┌─────────┬───────┬──────┬────┐
│123456789│1234567│abcdef│abcd│
└─────────┴───────┴──────┴────┘
   
   (;:'length literal') , ((;~ #)&> \: #S:0) ;: A  NB. box incompatible types with header
┌──────┬─────────┐
│length│literal  │
├──────┼─────────┤
│9     │123456789│
├──────┼─────────┤
│7     │1234567  │
├──────┼─────────┤
│6     │abcdef   │
├──────┼─────────┤
│4     │abcd     │
└──────┴─────────┘

   (;:'len vector') , ((;~ #)&> \: #S:0) 0 1 2 3 ; 0 1 ; (i. 8) ; 0
┌───┬───────────────┐
│len│vector         │
├───┼───────────────┤
│8  │0 1 2 3 4 5 6 7│
├───┼───────────────┤
│4  │0 1 2 3        │
├───┼───────────────┤
│2  │0 1            │
├───┼───────────────┤
│1  │0              │
└───┴───────────────┘

Java

Works with: Java version 11
Works with: Java version 17
package stringlensort;

import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;

public class ReportStringLengths {

    public static void main(String[] args) {
        String[] list = {"abcd", "123456789", "abcdef", "1234567"};
        String[] strings = args.length > 0 ? args : list;

        compareAndReportStringsLength(strings);
    }

    /**
     * Compare and report strings length to System.out.
     * 
     * @param strings an array of strings
     */    
    public static void compareAndReportStringsLength(String[] strings) {
        compareAndReportStringsLength(strings, System.out);
    }

    /**
     * Compare and report strings length.
     * 
     * @param strings an array of strings
     * @param stream the output stream to write results
     */
    public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {
        if (strings.length > 0) {
            strings = strings.clone();
            final String QUOTE = "\"";
            Arrays.sort(strings, Comparator.comparing(String::length));
            int min = strings[0].length();
            int max = strings[strings.length - 1].length();
            for (int i = strings.length - 1; i >= 0; i--) {
                int length = strings[i].length();
                String predicate;
                if (length == max) {
                    predicate = "is the longest string";
                } else if (length == min) {
                    predicate = "is the shortest string";
                } else {
                    predicate = "is neither the longest nor the shortest string";
                }
                //@todo: StringBuilder may be faster
                stream.println(QUOTE + strings[i] + QUOTE + " has length " + length
                        + " and " + predicate);
            }
        }
    }
}
Output:
"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

JavaScript

JavaScript (ECMA Script) file stringlensort.js.

/**
 * Compare and report strings lengths.
 * 
 * @param {Element} input - a TextArea DOM element with input
 * @param {Element} output - a TextArea DOM element for output
 */
function compareStringsLength(input, output) {

  // Safe defaults.
  //
  output.value = "";
  let output_lines = [];

  // Split input into an array of lines.
  //
  let strings = input.value.split(/\r\n|\r|\n/g);

  // Is strings array empty?
  //
  if (strings && strings.length > 0) {

    // Remove leading and trailing spaces.
    //
    for (let i = 0; i < strings.length; i++)
      strings[i] = strings[i].trim();

    // Sort by lengths.
    //
    strings.sort((a, b) => a.length - b.length);

    // Remove empty strings.
    //
    while (strings[0] == "")
      strings.shift();

    // Check if any strings remain.
    //
    if (strings && strings.length > 0) {

      // Get min and max length of strings.
      //
      const min = strings[0].length;
      const max = strings[strings.length - 1].length;

      // Build output verses - longest strings first.
      //
      for (let i = strings.length - 1; i >= 0; i--) {
        let length = strings[i].length;
        let predicate;
        if (length == max) {
          predicate = "is the longest string";
        } else if (length == min) {
          predicate = "is the shortest string";
        } else {
          predicate = "is neither the longest nor the shortest string";
        }
        output_lines.push(`"${strings[i]}" has length ${length} and ${predicate}\n`);
      }

      // Send all lines from output_lines array to an TextArea control.
      //
      output.value = output_lines.join('');
    }
  }
}

document.getElementById("input").value = "abcd\n123456789\nabcdef\n1234567";
compareStringsLength(input, output);

HTML file (with embeded CSS) to run the script.

<html>

<head>
  <style>
    div {
      margin-top: 4ch;
      margin-bottom: 4ch;
    }

    label {
      display: block;
      margin-bottom: 1ch;
    }

    textarea {
      display: block;
    }

    input {
      display: block;
      margin-top: 4ch;
      margin-bottom: 4ch;
    }
  </style>
</head>

<body>
  <main>
    <form>
      <div>
        <label for="input">Input:
        </label>
        <textarea rows="20" cols="80" id="input"></textarea>
      </div>
      <input type="button" value="press to compare strings" onclick="compareStringsLength(input, output);">
      </input>
      <div>
        <label for="output">Output:
        </label>
        <textarea rows="20" cols="80" id="output"></textarea>
      </div>
    </form>
  </main>
  <script src="stringlensort.js"></script>
</body>

</html>
Output:
"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

Julia

Per the Julia docs, a String in Julia is a sequence of characters encoded as UTF-8. Most string methods in Julia actually accept an AbstractString, which is the supertype of strings in Julia regardless of the encoding, including the default UTF-8.

The Char data type in Julia is a 32-bit, potentially Unicode data type, so that if we enumerate a String as a Char array, we get a series of 32-bit characters:

s = "niño"
println("Position  Char Bytes\n==============================")
for (i, c) in enumerate(s)
    println("$i          $c     $(sizeof(c))")
end
Output:
Position  Char Bytes
==============================
1          n     4
2          i     4
3          ñ     4
4          o     4

However, if we index into the string, the index into the string will function as if the string was an ordinary C string, that is, an array of unsigned 8-bit integers. If the index attempts to index within a character of size greater than one byte, an error is thrown for bad indexing. This can be demonstrated by casting the above string to codeunits:

println("Position  Codeunit Bytes\n==============================")
for (i, c) in enumerate(codeunits(s))
    println("$i            $(string(c, base=16))     $(sizeof(c))")
end
Output:
Position  Codeunit Bytes
==============================
1            6e     1
2            69     1
3            c3     1
4            b1     1
5            6f     1

Note that the length of "niño" as a String is 4 characters, and the length of "niño" as codeunits (ie, 8 bit bytes) is 5. Indexing into the 4th position results in an error:

julia> s[4]
ERROR: StringIndexError: invalid index [4], valid nearby indices [3]=>'ñ', [5]=>'o'

So, whether a string is longer or shorter depends on the encoding, as below:

length("ñññ") < length("nnnn")  # true, and the usual meaning of length of a String

length(codeunits("ñññ")) > length(codeunits("nnnn"))  # true as well

jq

Works with: jq

Works with gojq, the Go implementation of jq

def s1: "longer";
def s2: "shorter😀";

[s1,s2]
| sort_by(length)
| reverse[]
| "\"\(.)\" has length (codepoints) \(length) and utf8 byte length \(utf8bytelength)."
Output:
"shorter😀" has length (codepoints) 8 and utf8 byte length 11.
"longer" has length (codepoints) 6 and utf8 byte length 6.

Lambdatalk

Lambdatalk comes with primitives working on words, [W.equal?, W.length, ...], on sentences, [S.empty?, S.first, S.rest, ...] and pairs, [P.new, P.left, P.right, ...].

Using these primitives we define 2 helper functions, [L.new, L.disp], to build and display a list according to a chosen format.

{def L.new
 {lambda {:s}
  {if {S.empty? {S.rest :s}}
   then {P.new {S.first :s} nil}
   else {P.new {S.first :s} {L.new {S.rest :s}}}}}}
-> L.new 

{def L.disp
 {lambda {:l}
  {if {W.equal? :l nil}
   then 
   else {br} {W.length {P.left :l}} : {P.left :l}
        {L.disp {P.right :l}}}}}
-> L.disp

For instance

{def B {L.new abcd 123456789 abcdef 1234567}}
-> B

{L.disp {B}}
-> 
 4 : abcd 
 9 : 123456789 
 6 : abcdef 
 7 : 1234567

Then we define the L.sort function waiting for a predicate function and a list.

{def L.sort
 {lambda {:filter :l} 
  {if {W.equal? :l nil} 
   then nil 
   else {L.insert {P.left :l} :filter
                  {L.sort :filter {P.right :l}}}}}}
-> L.sort

{def L.insert
 {lambda {:x :filter :l} 
  {if {W.equal? :l nil} 
   then {P.new :x nil} 
   else {if {:filter :x {P.left :l}} 
   then {P.new :x :l} 
   else {P.new {P.left :l}
              {L.insert :x :filter {P.right :l}}}}}}}
-> L.insert

Using the following predicate function (which could be anonymous) testing the length of 2 words

{def filter
 {lambda {:a :b}
  {> {W.length :a} {W.length :b}}}}
-> filter

we display the B list sorted according to the length of its elements.

{L.disp {L.sort filter {B}}}
-> 
 9 : 123456789 
 7 : 1234567 
 6 : abcdef 
 4 : abcd

Note that in lambdatalk words (and numbers) don't need to be quoted.

Lua

function test(list)
  table.sort(list, function(a,b) return #a > #b end)
  for _,s in ipairs(list) do print(#s, s) end
end
test{"abcd", "123456789", "abcdef", "1234567"}
Output:
9       123456789
7       1234567
6       abcdef
4       abcd

Mathematica / Wolfram Language

list = {"abcd", "123456789", "abcdef", "1234567"};
Reverse@SortBy[list, StringLength] // TableForm
Output:

123456789 1234567 abcdef abcd

Nim

In Nim, a character (char) is represented on a byte. A string is a sequence of characters with a length. For interoperability reason, an extra null is added at the end of the characters. A string is supposed to be encoded in UTF-8, but this is not enforced. The function len returns the length of the string i.e. its number of characters (without the extra null).

If we want to manage a string as a Unicode sequence of code points, we have to use the module unicode. We can convert a string in a sequence of runes, each rune being a unicode UTF-32 value. The length of this sequence is the number of code points.

import strformat, unicode

const
  S1 = "marche"
  S2 = "marché"

echo &"“{S2}”, byte length = {S2.len}, code points: {S2.toRunes.len}"
echo &"“{S1}”, byte length = {S1.len}, code points: {S1.toRunes.len}"
Output:
“marché”, byte length = 7, code points: 6
“marche”, byte length = 6, code points: 6

Pascal

Works with: Extended Pascal
program compareLengthOfStrings(output);

const
	specimenA = 'RosettaCode';
	specimenB = 'Pascal';
	specimenC = 'Foobar';
	specimenD = 'Pascalish';

type
	specimen = (A, B, C, D);
	specimens = set of specimen value [];

const
	specimenMinimum = A;
	specimenMaximum = D;

var
	{ the explicit range min..max serves as a safeguard to update max const }
	list: array[specimenMinimum..specimenMaximum] of string(24)
		value [A: specimenA; B: specimenB; C: specimenC; D: specimenD];
	lengthRelationship: array[specimen] of specimens;

procedure analyzeLengths;
var
	left, right: specimen;
begin
	for left := specimenMinimum to specimenMaximum do
	begin
		for right := specimenMinimum to specimenMaximum do
		begin
			if length(list[left]) < length(list[right]) then
			begin
				lengthRelationship[right] := lengthRelationship[right] + [right]
			end
		end
	end
end;

procedure printSortedByLengths;
var
	i: ord(specimenMinimum)..ord(specimenMaximum);
	s: specimen;
begin
	{ first the string longer than all other strings }
	{ lastly print the string not longer than any other string }
	for i := ord(specimenMaximum) downto ord(specimenMinimum) do
	begin
		{ for demonstration purposes: iterate over a set }
		for s in [specimenMinimum..specimenMaximum] do
		begin
			{ card returns the cardinality ("population count") }
			if card(lengthRelationship[s]) = i then
			begin
				writeLn(length(list[s]):8, ' ', list[s])
			end
		end
	end
end;

begin
	analyzeLengths;
	printSortedByLengths
end.
Output:
      11 RosettaCode
       9 Pascalish
       6 Pascal
       6 Foobar

Perl

#!/usr/bin/perl

use strict; # https://rosettacode.org/wiki/Compare_length_of_two_strings
use warnings;

for ( 'shorter thelonger', 'abcd 123456789 abcdef 1234567' )
  {
  print "\nfor strings => $_\n";
  printf "length %d: %s\n", length(), $_
    for sort { length $b <=> length $a } split;
  }
Output:

for strings => shorter thelonger
length 9: thelonger
length 7: shorter

for strings => abcd 123456789 abcdef 1234567
length 9: 123456789
length 7: 1234567
length 6: abcdef
length 4: abcd

Phix

Lengths are in bytes, for codepoints use length(utf8_to_utf32()) or similar.

with javascript_semantics
sequence list = {"abcd","123456789","abcdef","1234567"},
         lens = apply(list,length),
         tags = reverse(custom_sort(lens,tagset(length(lens))))
papply(true,printf,{1,{"%s (length %d)\n"},columnize({extract(list,tags),extract(lens,tags)})})
Output:
123456789 (length 9)
1234567 (length 7)
abcdef (length 6)
abcd (length 4)

PHP

<?php


function retrieveStrings()
{
    if (isset($_POST['input'])) {
        $strings = explode("\n", $_POST['input']);
    } else {
        $strings = ['abcd', '123456789', 'abcdef', '1234567'];
    }
    return $strings;
}


function setInput()
{
    echo join("\n", retrieveStrings());
}


function setOutput()
{
    $strings = retrieveStrings();

    // Remove empty strings
    //
    $strings = array_map('trim', $strings);
    $strings = array_filter($strings);

    if (!empty($strings)) {
        usort($strings, function ($a, $b) {
            return strlen($b) - strlen($a);
        });
        $max_len = strlen($strings[0]);
        $min_len = strlen($strings[count($strings) - 1]);
        foreach ($strings as $s) {
            $length = strlen($s);
            if ($length == $max_len) {
                $predicate = "is the longest string";
            } elseif ($length == $min_len) {
                $predicate = "is the shortest string";
            } else {
                $predicate = "is neither the longest nor the shortest string";
            }
            echo "$s has length $length and $predicate\n";
        }
    }
}

?>


<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        div {
            margin-top: 4ch;
            margin-bottom: 4ch;
        }

        label {
            display: block;
            margin-bottom: 1ch;
        }

        textarea {
            display: block;
        }

        input {
            display: block;
            margin-top: 4ch;
            margin-bottom: 4ch;
        }
    </style>
</head>


<body>
    <main>
        <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8">
            <div>
                <label for="input">Input:
                </label>
                <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea>
                </label>
            </div>
            <input type="submit" value="press to compare strings">
            </input>
            <div>
                <label for="Output">Output:
                </label>
                <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea>
            </div>
        </form>
    </main>
</body>

</html>

PL/I

   declare (S1, S2) character (20) varying; /* 11 Aug 2022 */
   get (S1, S2);
   if length(S1) > length(S2) then
      put (length(S1), S1);
   else
      put (length(S2), S2);

Python

Naive solution

Works with: Python version 3.8
A = 'I am string'
B = 'I am string too'

if len(A) > len(B):
    print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings')
    print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings')
elif len(A) < len(B):
    print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings')
    print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings')
else:
    print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string')
    print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
Output:
"I am string too" has length 15 and is the longest of the two strings
"I am string" has length 11 and is the shortest of the two strings

Advanced solution

Works with: Python version 3.8

The solution below has some imperfection. When the longest strings of characters are of equal length, instead of describing them as "one of the longest" they are described as "the longest". This works similarly for the shortest strings. Also, if all strings (in this case where there is only one) have the same length it is not printed that they are the shortest strings. Of course, this could be improved.

"""
An example code for the task "Compare length of two strings" (Rosseta Code).

This example code can handle not only strings, but any objects.
"""


def _(message):
    """Translate: an placeholder for i18n and l10n gettext or similar."""
    return message


def compare_and_report_length(*objects, sorted_=True, reverse=True):
    """
    For objects given as parameters it prints which of them are the longest.

    So if the parameters are strings, then the strings are printed, their
    lengths and classification as the longest, shortest or average length.

    Note that for N > 0 such objects (e.g., strings, bytes, lists) it is
    possible that exactly M > 0 of them will be of the maximum length, K > 0 of
    them will be of the minimum length. In particular, it is possible that all
    objects will be exactly the same length. So we assume that if an object has
    both the maximum and minimum length, it is referred to as a string with the
    maximum length.

    Args:
        *objects (object): Any objects with defined length.
        sorted_ (bool, optional): If sorted_ is False then objects are not
                sorted. Defaults to True.
        reverse (bool, optional): If reverse is True and sorted_ is True
                objects are sorted in the descending order. If reverse is False
                and sorted_ is True objects are sorted in the ascending order.
                Defaults to True.

    Returns:
        None.
    """
    lengths = list(map(len, objects))
    max_length = max(lengths)
    min_length = min(lengths)
    lengths_and_objects = zip(lengths, objects)

    # Longer phrases make translations into other natural languages easier.
    #
    has_length = _('has length')
    if all(isinstance(obj, str) for obj in objects):
        predicate_max = _('and is the longest string')
        predicate_min = _('and is the shortest string')
        predicate_ave = _('and is neither the longest nor the shortest string')
    else:
        predicate_max = _('and is the longest object')
        predicate_min = _('and is the shortest object')
        predicate_ave = _('and is neither the longest nor the shortest object')

    if sorted_:
        lengths_and_objects = sorted(lengths_and_objects, reverse=reverse)

    for length, obj in lengths_and_objects:
        if length == max_length:
            predicate = predicate_max
        elif length == min_length:
            predicate = predicate_min
        else:
            predicate = predicate_ave
        print(obj, has_length, length, predicate)


A = 'I am string'
B = 'I am string too'
LIST = ["abcd", "123456789", "abcdef", "1234567"]


print('Two strings')
print()
compare_and_report_length(A, B)
print()

print('A list of strings')
print()
compare_and_report_length(*LIST)
print()
Output:
Two strings

"I am string too" has length 15 and is the longest string
"I am string" has length 11 and is the shortest string

A list of strings

"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

QB64

Dim Words(1 To 4) As String
Dim Lengths As Integer, Index As Integer, Position As Integer, Done As String, Index2 As Integer
' inititialization
Words(1) = "abcd"
Words(2) = "123456789"
Words(3) = "abcdef"
Words(4) = "1234567"

Print " Word         Length"
For Index2 = 1 To 4 Step 1
    Lengths = 0
    Position = 0
    For Index = 1 To 4 Step 1
        If Lengths < Len(Words(Index)) And InStr(Done, Words(Index) + " ") = 0 Then
            Lengths = Len(Words(Index))
            Position = Index
        End If
    Next Index
    Done = Done + Words(Position) + " /@/"
    Print Words(Position), Len(Words(Position))
Next Index2

Quackery

  $ "A short string of"
  $ "A slightly longer string of"
   
  2dup size dip size > if swap 
  dup echo$ sp size echo say " characters." cr
  dup echo$ sp size echo say " characters." cr cr

  '  [ $ "From troubles of the world I turn to ducks,"
       $ "Beautiful comical things"
       $ "Sleeping or curled"
       $ "Their heads beneath white wings"
       $ "By water cool,"
       $ "Or finding curious things"
       $ "To eat in various mucks"
       $ "Beneath the pool," ] 
   []  swap witheach [ do nested join ]
 
  sortwith [ size dip size < ]
  witheach [ echo$ cr ]
Output:
A slightly longer string of 27 characters.
A short string of 17 characters.

From troubles of the world I turn to ducks,
Their heads beneath white wings
Or finding curious things
Beautiful comical things
To eat in various mucks
Sleeping or curled
Beneath the pool,
By water cool,

Raku

So... In what way does this task differ significantly from String length? Other than being horribly under specified?

In the modern world, string "length" is pretty much a useless measurement, especially in the absence of a specified encoding; hence Raku not even having an operator: "length" for strings.

say 'Strings (👨‍👩‍👧‍👦, 🤔🇺🇸, BOGUS!) sorted: "longest" first:';
say "$_: characters:{.chars},  Unicode code points:{.codes},  UTF-8 bytes:{.encode('UTF8').bytes},  UTF-16 bytes:{.encode('UTF16').bytes}" for <👨‍👩‍👧‍👦 BOGUS! 🤔🇺🇸>.sort: -*.chars;
Output:
Strings (👨‍👩‍👧‍👦, 🤔🇺🇸, BOGUS!) sorted: "longest" first:
BOGUS!: characters:6,  Unicode code points:6,  UTF-8 bytes:6,  UTF-16 bytes:12
🤔🇺🇸: characters:2,  Unicode code points:3,  UTF-8 bytes:12,  UTF-16 bytes:12
👨‍👩‍👧‍👦: characters:1,  Unicode code points:7,  UTF-8 bytes:25,  UTF-16 bytes:22

REXX

/* REXX */
list = '"abcd","123456789","abcdef","1234567"'
Do i=1 By 1 While list>''
  Parse Var list s.i ',' list
  s.i=strip(s.i,,'"')
  End
n=i-1
Do While n>1
  max=0
  Do i=1 To n
    If length(s.i)>max Then Do
      k=i
      max=length(s.i)
      End
    End
  Call o s.k
  If k<n Then
    s.k=s.n
  n=n-1
  End
Call o s.1
Exit
o:
Say length(arg(1)) arg(1)
Return
Output:
9 123456789
7 1234567
6 abcdef
4 abcd

Ring

Two strings

see "working..." + nl

list = ["abcd","123456789"]
if len(list[1]) > len(list[2])
   first = list[1]
   second = list[2]
else
   first = list[2]
   second = list[1]
ok

see "Compare length of two strings:" + nl
see "" + first + " len = " + len(first) + nl + second + " len = " + len(second) + nl
see "done..." + nl
Output:
working...
Compare length of two strings:
123456789 len = 9
abcd len = 4
done...

More than two strings

see "working..." + nl

lenList = []
list = ["abcd","123456789","abcdef","1234567"]
for n = 1 to len(list)
    len = len(list[n])
    add(lenList,[len,n])
next

lenList = sort(lenList,1)
lenList = reverse(lenList)

see "Compare length of strings in descending order:" + nl
for n = 1 to len(lenList)
    see "" + list[lenList[n][2]] + " len = " + lenList[n][1] + nl
next
see "done..." + nl
Output:
working...
Compare length of strings in descending order:
123456789 len = 9
1234567 len = 7
abcdef len = 6
abcd len = 4
done...

Ruby

a, b = "Given two strings", "of different length"
[a,b].sort_by{|s| - s.size }.each{|s| puts s + " (size: #{s.size})"}

list = ["abcd","123456789","abcdef","1234567"]
puts list.sort_by{|s|- s.size}
Output:
of different length (size: 19)
Given two strings (size: 17)
123456789
1234567
abcdef
abcd

Rust

fn compare_and_report<T: ToString>(string1: T, string2: T) -> String {
    let strings = [string1.to_string(), string2.to_string()];
    let difference = strings[0].len() as i32 - strings[1].len() as i32;
    if difference == 0 { // equal
        format!("\"{}\" and \"{}\" are of equal length, {}", strings[0], strings[1], strings[0].len())
    } else if difference > 1 { // string1 > string2
        format!("\"{}\" has length {} and is the longest\n\"{}\" has length {} and is the shortest", strings[0], strings[0].len(), strings[1], strings[1].len())
    } else { // string2 > string1
        format!("\"{}\" has length {} and is the longest\n\"{}\" has length {} and is the shortest", strings[1], strings[1].len(), strings[0], strings[0].len())
    }
}

fn main() {
    println!("{}", compare_and_report("a", "b"));
    println!("\n{}", compare_and_report("cd", "e"));
    println!("\n{}", compare_and_report("f", "gh"));
}
Output:
"a" and "a" are of equal length, 1

"d" has length 1 and is the longest  
"bc" has length 2 and is the shortest

"fg" has length 2 and is the longest 
"e" has length 1 and is the shortest

Vlang

// Compare lenth of two strings, in V
// Tectonics: v run compare-length-of-two-strings.v
module main

// starts here
pub fn main() {
    mut strs := ["abcd","123456789"]
    println("Given: $strs")
    strs.sort_by_len()
    for i := strs.len-1; i >= 0; i-- {
        println("${strs[i]}: with length ${strs[i].len}")
    }

    // more than 2 strings. note = vs :=, := for definition, = for assignment
    strs = ["abcd","123456789","abcdef","1234567"]
    println("\nGiven: $strs")
    strs.sort_by_len()
    for i := strs.len-1; i >= 0; i-- {
        println("${strs[i]}: with length ${strs[i].len}")
    }
}
Output:
prompt$ v run compare-length-of-two-strings.v
Given: ['abcd', '123456789']
123456789: with length 9
abcd: with length 4

Given: ['abcd', '123456789', 'abcdef', '1234567']
123456789: with length 9
1234567: with length 7
abcdef: with length 6
abcd: with length 4

Wren

Library: Wren-upc

In Wren a string (i.e. an object of the String class) is an immutable sequence of bytes which is usually interpreted as UTF-8 but does not have to be.

With regard to string length, the String.count method returns the number of 'codepoints' in the string. If the string contains bytes which are invalid UTF-8, each such byte adds one to the count.

To find the number of bytes one can use String.bytes.count.

Unicode grapheme clusters, where what appears to be a single 'character' may in fact be an amalgam of several codepoints, are not directly supported by Wren but it is possible to measure the length in grapheme clusters of a string (i.e. the number of user perceived characters) using the Graphemes.clusterCount method of the Wren-upc module.

import "./upc" for Graphemes

var printCounts = Fn.new { |s1, s2, c1, c2|
   var l1 = (c1 > c2) ? [s1, c1] : [s2, c2]
   var l2 = (c1 > c2) ? [s2, c2] : [s1, c1]
   System.print(  "%(l1[0]) : length %(l1[1])")
   System.print(  "%(l2[0]) : length %(l2[1])\n")
}

var codepointCounts = Fn.new { |s1, s2|
   var c1 = s1.count
   var c2 = s2.count
   System.print("Comparison by codepoints:")
   printCounts.call(s1, s2, c1, c2)
}

var byteCounts = Fn.new { |s1, s2|
   var c1 = s1.bytes.count
   var c2 = s2.bytes.count
   System.print("Comparison by bytes:")
   printCounts.call(s1, s2, c1, c2)
}

var graphemeCounts = Fn.new { |s1, s2|
   var c1 = Graphemes.clusterCount(s1)
   var c2 = Graphemes.clusterCount(s2)
   System.print("Comparison by grapheme clusters:")
   printCounts.call(s1, s2, c1, c2)
}

for (pair in [ ["nino", "niño"], ["👨‍👩‍👧‍👦", "🤔🇺🇸"] ]) {
    codepointCounts.call(pair[0], pair[1])
    byteCounts.call(pair[0], pair[1])
    graphemeCounts.call(pair[0], pair[1])
}

var list = ["abcd", "123456789", "abcdef", "1234567"]
System.write("Sorting in descending order by length in codepoints:\n%(list) -> ")
list.sort { |a, b| a.count > b.count }
System.print(list)
Output:
Comparison by codepoints:
niño : length 4
nino : length 4

Comparison by bytes:
niño : length 5
nino : length 4

Comparison by grapheme clusters:
niño : length 4
nino : length 4

Comparison by codepoints:
👨‍👩‍👧‍👦 : length 7
🤔🇺🇸 : length 3

Comparison by bytes:
👨‍👩‍👧‍👦 : length 25
🤔🇺🇸 : length 12

Comparison by grapheme clusters:
🤔🇺🇸 : length 2
👨‍👩‍👧‍👦 : length 1

Sorting in descending order by length in codepoints:
[abcd, 123456789, abcdef, 1234567] -> [123456789, 1234567, abcdef, abcd]

XPL0

string 0;               \use zero-terminated string convention

func    StrLen(A);      \Return number of characters in an ASCIIZ string
char    A;
int     I;
for I:= 0 to -1>>1 do
        if A(I) = 0 then return I;

char    List;
int     M, N, SN, Len, Max;
[List:= ["abcd","123456789","abcdef","1234567"];
for M:= 0 to 3 do
    [Max:= 0;
    for N:= 0 to 3 do
        [Len:= StrLen(@List(N,0));
        if Len > Max then [Max:= Len;  SN:= N];
        ];
    Text(0, @List(SN,0));
    Text(0, " length is ");  IntOut(0, StrLen(@List(SN,0)));  CrLf(0);
    List(SN, 0):= 0;    \truncate largest string
    ];
]
Output:
123456789 length is 9
1234567 length is 7
abcdef length is 6
abcd length is 4

Z80 Assembly

Terminator equ 0      ;null terminator
PrintChar equ &BB5A   ;Amstrad CPC BIOS call, prints accumulator to screen as an ASCII character.

        org &8000

	ld hl,String1
	ld de,String2
	call CompareStringLengths
	
	jp nc, Print_HL_First
		ex de,hl
Print_HL_First:
	push bc
		push hl
			call PrintString
		pop hl
		push hl
			ld a,' '
			call PrintChar
			call getStringLength
			ld a,b
			call ShowHex_NoLeadingZeroes
			call NewLine
		pop hl
	pop bc
	
	ex de,hl
	push bc
		push hl
			call PrintString
		pop hl
		push hl
			ld a,' '
			call PrintChar
			call getStringLength
			ld a,b
			call ShowHex_NoLeadingZeroes
			call NewLine
		pop hl
	pop bc	
ReturnToBasic:
	RET

String1:
	byte "Hello",Terminator
String2:
	byte "Goodbye",Terminator

;;;;;; RELEVANT SUBROUTINES - PRINTSTRING AND NEWLINE CREATED BY KEITH S. OF CHIBIAKUMAS
CompareStringLengths:
	;HL = string 1
	;DE = string 2
	;CLOBBERS A,B,C
	push hl
	push de
	ex de,hl
	call GetStringLength
	ld b,c
	
	ex de,hl
	call GetStringLength
	ld a,b
	cp c
	pop de
	pop hl
	ret
	;returns carry set if HL < DE, zero set if equal, zero & carry clear if HL >= DE
	;returns len(DE) in C, and len(HL) in B.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
GetStringLength:
		ld b,0
loop_getStringLength:
		ld a,(hl)
		cp Terminator
		ret z
		inc hl
		inc b
		jr loop_getStringLength
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
NewLine:
	push af
	ld a,13		;Carriage return
	call PrintChar
	ld a,10		;Line Feed 
	call PrintChar
	pop af
	ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintString:
	ld a,(hl)	
	cp Terminator
	ret z
	inc hl
	call PrintChar
	jr PrintString
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ShowHex_NoLeadingZeroes:
;useful for printing values where leading zeroes don't make sense,
; 	such as money etc.
	push af
		and %11110000
		ifdef gbz80      ;game boy 
			swap a
		else             ;zilog z80
			rrca
			rrca
			rrca
			rrca
		endif
		or a
		call nz,PrintHexChar
		;if top nibble of A is zero, don't print it.
	pop af
	and %00001111
	or a
	ret z	;if bottom nibble of A is zero, don't print it!
	jp PrintHexChar
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintHexChar:
	or a	  ;Clear Carry Flag
	daa
	add a,&F0
	adc a,&40 ;This sequence converts a 4-bit hex digit to its ASCII equivalent.
	jp PrintChar
Output:
Goodbye 7
Hello 5