Compare length of two strings: Difference between revisions

m
no edit summary
m (Simplify Common Lisp)
mNo edit summary
(36 intermediate revisions by 16 users not shown)
Line 15:
{{Strings}}
<br><br>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program complength64.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
 
/************************************/
/* structures */
/************************************/
.struct 0
list_string: // string address
.struct list_string + 8
list_length: // string length
.struct list_length + 8
list_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "@ length : @\n"
szCarriageReturn: .asciz "\n"
szLibSort: .asciz "\nAfter sort\n"
szString1: .asciz "abcd"
szString2: .asciz "123456789"
szString3: .asciz "abcdef"
szString4: .asciz "1234567"
 
.align 4
tabStrings: .quad szString1 // string address array
.quad 0
.quad szString2
.quad 0
.quad szString3
.quad 0
.quad szString4
.quad 0
.equ NBTABSTRINGS, (. - tabStrings) / list_end // compute items number
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x4,qAdrtabStrings // string array address
mov x5,#0 // indice
mov x6,#list_end // structure size
1: // item loop
madd x3,x5,x6,x4 // compute item address
ldr x0,[x3,#list_string] // load string address
bl stringRoutine // length string compute
str x0,[x3,#list_length] // store result in array
add x5,x5,#1 // increment indice
cmp x5,#NBTABSTRINGS // end ?
blt 1b // no -> loop
mov x0,x4 // string array address
mov x1,#0 // first item
mov x2,#NBTABSTRINGS // item number
bl insertionSort // sort
ldr x0,qAdrszLibSort
bl affichageMess
mov x0,x4 // string array address
mov x5,#0 // indice
mov x6,#list_end
2: // item loop
madd x3,x5,x6,x4
ldr x0,[x3,#list_string]
bl stringRoutine // use same routine for display result after sort
add x5,x5,#1
cmp x5,#NBTABSTRINGS // end ?
blt 2b // no -> loop
 
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessResult: .quad szMessResult
qAdrsZoneConv: .quad sZoneConv
qAdrtabStrings: .quad tabStrings
qAdrszLibSort: .quad szLibSort
/***************************************************/
/* string exec */
/***************************************************/
// x0 contains string address
// x0 return length
stringRoutine:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x3,x0 // save string address
mov x1,x0
ldr x0,qAdrszMessResult
bl strInsertAtCharInc // insert string in result message
mov x2,x0 // save new message address
mov x0,x3 // restaur string address
bl stringlength // compute length
mov x3,x0
ldr x1,qAdrsZoneConv
bl conversion10 // call decimal conversion
mov x0,x2
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess // display result message
mov x0,x3
100:
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* compute string length */
/***************************************************/
// x0 contains string address
stringlength:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x1,#-1 // init counter
1: // loop
add x1,x1,#1 // increment counter
ldrb w2,[x0,x1] // load byte string
cmp w2,#0 // zero final ?
bne 1b // no -> loop
mov x0,x1 // return length
100:
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
 
/******************************************************************/
/* insertion sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first element */
/* x2 contains the number of element */
insertionSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
stp x10,x11,[sp,-16]! // save registers
mov x6,x0
mov x7,#list_end
add x3,x1,#1 // start index i
1: // start loop
madd x8,x7,x3,x6
ldr x10,[x8,#list_length] // load value A[i]
ldr x0,[x8,#list_string] // load string address A[i]
sub x5,x3,#1 // index j
2:
madd x9,x7,x5,x6
ldr x4,[x9,#list_length] // load value A[j]
cmp x4,x10 // compare value
bge 3f
add x5,x5,#1 // increment index j
madd x8,x7,x5,x6
str x4,[x8,#list_length] // store value A[j+1]
ldr x4,[x9,#list_string] // load string address
str x4,[x8,#list_string] // store string address
subs x5,x5,#2 // j = i - 1
cmp x5,x1 // compare with first item
bge 2b // loop if j >= first item
3:
add x5,x5,#1 // increment index j
madd x9,x7,x5,x6
str x10,[x9,#list_length] // store value A[i] in A[j+1]
str x0,[x9,#list_string] // and store string address
add x3,x3,#1 // increment index i
cmp x3,x2 // end ?
blt 1b // no -> loop
 
100:
ldp x10,x11,[sp],16 // restaur registers
ldp x8,x9,[sp],16 // restaur registers
ldp x6,x7,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
abcd length : 4
123456789 length : 9
abcdef length : 6
1234567 length : 7
 
After sort
123456789 length : 9
1234567 length : 7
abcdef length : 6
abcd length : 4
</pre>
=={{header|Ada}}==
 
Line 88 ⟶ 297:
3 abc
</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang ARM Assembly>
/* ARM assembly Raspberry PI or android 32 bits */
/* program complength.s */
 
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
 
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
/************************************/
/* structures */
/************************************/
.struct 0
list_string: @ string address
.struct list_string + 4
list_length: @ string length
.struct list_length + 4
list_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "@ length : @\n"
szCarriageReturn: .asciz "\n"
szLibSort: .asciz "\nAfter sort\n"
szString1: .asciz "abcd"
szString2: .asciz "123456789"
szString3: .asciz "abcdef"
szString4: .asciz "1234567"
 
.align 4
tabStrings: .int szString1 @ string address array
.int 0
.int szString2
.int 0
.int szString3
.int 0
.int szString4
.int 0
.equ NBTABSTRINGS, (. - tabStrings) / list_end @ compute items number
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r4,iAdrtabStrings @ string array address
mov r5,#0 @ indice
mov r6,#list_end @ structure size
1: @ item loop
mla r3,r5,r6,r4 @ compute item address
ldr r0,[r3,#list_string] @ load string address
bl stringRoutine @ length string compute
str r0,[r3,#list_length] @ store result in array
add r5,#1 @ increment indice
cmp r5,#NBTABSTRINGS @ end ?
blt 1b @ no -> loop
mov r0,r4 @ string array address
mov r1,#0 @ first item
mov r2,#NBTABSTRINGS @ item number
bl insertionSort @ sort
ldr r0,iAdrszLibSort
bl affichageMess
mov r0,r4 @ string array address
mov r5,#0 @ indice
mov r6,#list_end
2: @ item loop
mla r3,r5,r6,r4
ldr r0,[r3,#list_string]
bl stringRoutine @ use same routine for display result after sort
add r5,#1
cmp r5,#NBTABSTRINGS @ end ?
blt 2b @ no -> loop
 
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessResult: .int szMessResult
iAdrsZoneConv: .int sZoneConv
iAdrtabStrings: .int tabStrings
iAdrszLibSort: .int szLibSort
/***************************************************/
/* string exec */
/***************************************************/
// r0 contains string address
// r0 return length
stringRoutine:
push {r1-r3,lr} @ save registers
mov r3,r0 @ save string address
mov r1,r0
ldr r0,iAdrszMessResult
bl strInsertAtCharInc @ insert string in result message
mov r2,r0 @ save new message address
mov r0,r3 @ restaur string address
bl stringlength @ compute length
mov r3,r0
ldr r1,iAdrsZoneConv
bl conversion10 @ call decimal conversion
mov r0,r2
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess @ display result message
mov r0,r3
100:
pop {r1-r3,pc} @ restaur registers
/***************************************************/
/* compute string length */
/***************************************************/
// r0 contains string address
stringlength:
push {r1-r2,lr} @ save registers
mov r1,#-1 @ init counter
1: @ loop
add r1,#1 @ increment counter
ldrb r2,[r0,r1] @ load byte string
cmp r2,#0 @ zero final ?
bne 1b @ no -> loop
mov r0,r1 @ return length
100:
pop {r1-r2,pc} @ restaur registers
/******************************************************************/
/* insertion sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element */
/* r2 contains the number of element */
insertionSort:
push {r1-r10,lr} @ save registers
mov r6,r0
mov r7,#list_end
add r3,r1,#1 @ start index i
1: @ start loop
mla r8,r7,r3,r6
ldr r10,[r8,#list_length] @ load value A[i]
ldr r0,[r8,#list_string] @ load string address A[i]
sub r5,r3,#1 @ index j
2:
mla r9,r7,r5,r6
ldr r4,[r9,#list_length] @ load value A[j]
cmp r4,r10 @ compare value
bge 3f
add r5,#1 @ increment index j
mla r8,r7,r5,r6
str r4,[r8,#list_length] @ store value A[j+1]
ldr r4,[r9,#list_string] @ load string address
str r4,[r8,#list_string] @ store string address
subs r5,#2 @ j = i - 1
cmp r5,r1 @ compare with first item
bge 2b @ loop if j >= first item
3:
add r5,#1 @ increment index j
mla r9,r7,r5,r6
str r10,[r9,#list_length] @ store value A[i] in A[j+1]
str r0,[r9,#list_string] @ and store string address
add r3,#1 @ increment index i
cmp r3,r2 @ end ?
blt 1b @ no -> loop
 
100:
pop {r1-r10,lr}
bx lr
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
abcd length : 4
123456789 length : 9
abcdef length : 6
1234567 length : 7
 
After sort
123456789 length : 9
1234567 length : 7
abcdef length : 6
abcd length : 4
</pre>
 
=={{header|Arturo}}==
Line 317 ⟶ 723:
 
call comp("abcd", "123456789")</syntaxhighlight>
</syntaxhighlight>
 
==={{header|GWBASICChipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
The [[#True BASIC|True BASIC]] solution works without any changes.
 
==={{header|Gambas}}===
<syntaxhighlight lang="vbnet">Public Sub Main()
Compare("abcd", "123456789")
End
 
Sub Compare(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</syntaxhighlight>
 
==={{header|GW-BASIC}}===
{{works with|BASICA}}
{{works with|QBasic|1.1}}
Line 380 ⟶ 808:
End of program execution.
</pre>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|Just BASIC}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
{{works with|True BASIC}}
{{trans|True BASIC}}
<syntaxhighlight lang="qbasic">100 LET A$ = "abcd"
110 LET B$ = "123456789"
120 GOSUB 140
130 END
140 REM SUB comp(A$, B$)
150 IF LEN(A$) >= LEN(B$) THEN PRINT A$,LEN(A$) : PRINT B$,LEN(B$)
180 IF LEN(A$) < LEN(B$) THEN PRINT B$,LEN(B$) : PRINT A$,LEN(A$)
220 RETURN</syntaxhighlight>
 
==={{header|PureBasic}}===
Line 400 ⟶ 847:
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{works with|Chipmunk Basic}}
{{works with|True BASIC}}
<syntaxhighlight lang="qbasic">SUB comp(A$, B$)
Line 426 ⟶ 874:
 
call comp "abcd", "123456789"</syntaxhighlight>
 
==={{header|SmallBASIC}}===
<syntaxhighlight lang="qbasic">
func compfun(x, y)
if(len(x) == len(y))
return 0
elseif(len(x) > len(y))
return -1
else
return 1
endif
end
 
list = ["abcd","123456789","abcdef","1234567"]
 
sort list use compfun(x, y)
 
for s in list
print s, len(s)
next
</syntaxhighlight>
 
 
==={{header|True BASIC}}===
{{works with|QBasic}}
{{works with|Chipmunk Basic}}
<syntaxhighlight lang="qbasic">SUB comp(A$, B$)
IF LEN(A$) >= LEN(B$) THEN
Line 444 ⟶ 915:
<pre>Igual que la entrada de FreeBASIC.
</pre>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "Compare length of two strings"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
DECLARE FUNCTION comp (A$, B$)
 
 
FUNCTION Entry ()
comp("abcd", "123456789")
END FUNCTION
 
FUNCTION 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 FUNCTION
END PROGRAM</syntaxhighlight>
 
==={{header|Yabasic}}===
Line 623 ⟶ 1,118:
</pre>
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|10+}}
<syntaxhighlight lang="csharp">using System;
<syntaxhighlight lang="csharp">
using System.Collections.Generic;
void WriteSorted(string[] strings)
 
namespace example
{
var sorted = strings.OrderByDescending(x => x.Length);
class Program
foreach(var s in sorted) Console.WriteLine($"{s.Length}: {s}");
{
static void Main(string[] args)
{
var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(strings);
}
 
private static void compareAndReportStringsLength(string[] strings)
{
if (strings.Length > 0)
{
char Q = '"';
string hasLength = " has length ";
string predicateMax = " and is the longest string";
string predicateMin = " and is the shortest string";
string predicateAve = " and is neither the longest nor the shortest string";
string predicate;
 
(int, int)[] li = new (int, int)[strings.Length];
for (int i = 0; i < strings.Length; i++)
li[i] = (strings[i].Length, i);
Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);
int maxLength = li[0].Item1;
int minLength = li[strings.Length - 1].Item1;
 
for (int i = 0; i < strings.Length; i++)
{
int length = li[i].Item1;
string str = strings[li[i].Item2];
if (length == maxLength)
predicate = predicateMax;
else if (length == minLength)
predicate = predicateMin;
else
predicate = predicateAve;
Console.WriteLine(Q + str + Q + hasLength + length + predicate);
}
}
}
 
}
}
WriteSorted(new string[] { "abcd", "123456789", "abcdef", "1234567" });
</syntaxhighlight>
 
{{output}}
<pre>
<pre>"123456789" has length 9 and is the longest string
9: 123456789
"1234567" has length 7 and is neither the longest nor the shortest string
7: 1234567
"abcdef" has length 6 and is neither the longest nor the shortest string
6: abcdef
"abcd" has length 4 and is the shortest string
4: abcd
</pre>
 
Line 704 ⟶ 1,159:
R: 'abcdef' is 6 characters in length.
R: 'abcd' is 4 characters in length.
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
func stringLength a$ b$ . .
lineA$ = "\"" & a$ & "\" (length: " & len a$ & ")"
lineB$ = "\"" & b$ & "\" (length: " & len b$ & ")"
if len a$ >= len b$
print lineA$ ; print lineB$
else
print lineB$ ; print lineA$
.
.
call stringLength "Easy" "Language"
call stringLength "Rosetta" "Code"
</syntaxhighlight>
{{out}}
<pre>
"Language" (length: 8)
"Easy" (length: 4)
"Rosetta" (length: 7)
"Code" (length: 4)
</pre>
 
Line 743 ⟶ 1,176:
4 List
3 for
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|Classes,StdCtrls,SysUtils}}
Uses the Standard Delphi component TList compile the list of pointers to the strings and then sort them using a custom sort comparison.
 
<syntaxhighlight lang="Delphi">
var SA1: array [0..1] of string = ('Very Long String','short string');
var SA2: array [0..11] of string = ('Like','sands','through','the','hourglass',
'these','are','the','days','of','our','lives');
 
function Compare(P1,P2: pointer): integer;
{Compare for quick sort}
begin
Result:=Length(PString(P2)^)-Length(PString(P1)^);
end;
 
 
procedure ShowStringLengths(SA: array of string; Memo: TMemo);
{Sort strings by length and display string and length}
var List: TList;
var I: integer;
var S: string;
begin
List:=TList.Create;
try
for I:=0 to High(SA) do
List.Add(@SA[I]);
List.Sort(Compare);
for I:=0 to List.Count-1 do
begin
S:=PString(List[I])^;
Memo.Lines.Add(IntToStr(Length(S))+': '+S);
end;
finally List.Free; end;
end;
 
 
procedure SortedStringLists(Memo: TMemo);
{Test two different string arrays}
begin
Memo.Lines.Add('Two word test: ');
Memo.Lines.Add('');
ShowStringLengths(SA1,Memo);
Memo.Lines.Add('');
Memo.Lines.Add('Twelve word test: ');
Memo.Lines.Add('');
ShowStringLengths(SA2,Memo);
end;
 
</syntaxhighlight>
{{out}}
<pre>
Two word test:
 
16: Very Long String
12: short string
 
Twelve word test:
 
9: hourglass
7: through
5: lives
5: these
5: sands
4: days
4: Like
3: our
3: are
3: the
3: the
2: of
</pre>
 
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
proc scmp a$ b$ . .
if len a$ < len b$
swap a$ b$
.
print a$ & " - " & len a$
print b$ & " - " & len b$
print ""
.
scmp "Easy" "Language"
scmp "Rosetta" "Code"
</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">
(defun sort-list-by-string-length (list-of-strings)
"Order LIST-OF-STRINGS from longest to shortest."
(sort list-of-strings 'longer-string)) ; sort by "longer-string" function below
 
(defun longer-string (string-1 string-2)
"Test if STRING-1 is longer than STRING-2."
(> (length string-1) (length string-2))) ; is STRING-1 longer than STRING-2?
</syntaxhighlight>
{{out}}
(sort-list-by-string-length '("abcd" "123456789" "abcdef" "1234567"))
<pre>
("123456789" "1234567" "abcdef" "abcd")
</pre>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
List list = text["abcd","123456789","abcdef","1234567", "Привет, мир"]
^|this solves the task doing the comparison by using the diamond operator|^
fun comparator = int by text a, text b do return b.length <> a.length end
List sorted = list.sort(comparator)
writeLine("text".padEnd(15, " ") + "units".padStart(6, " ") + "bytes".padStart(6, " "))
for each text value in sorted
writeLine(value.padEnd(15, " ") +
(text!value.length).padStart(6, " ") +
^|conversion from text to blob uses utf8 encoding|^
(text!(blob!value).length).padStart(6, " "))
end
</syntaxhighlight>
{{out}}
<pre>
text units bytes
Привет, мир 11 20
123456789 9 9
1234567 7 7
abcdef 6 6
abcd 4 4
</pre>
 
Line 1,016 ⟶ 1,577:
 
=={{header|J}}==
<syntaxhighlight lang=J>
<pre>
NB. solution
chars=: 9&u:@>
longestFirst=: \: #@chars
lengthAndString=: ([:":@,.#@chars),.' ',.chars
 
NB. `Haruno-umi Hinemosu-Notari Notarikana'
NB. Spring ocean ; Swaying gently ; All day long.
 
,/lengthAndString _2 }.\ ": (;~ #)&> <@(7&u:);._2longestFirst '春の海 ';'ひねもすのたり ';'のたりかな '
7 ひねもすのたり
│3│春の海 │
│7│ひねもす5 のたりかな
│5│3 春たりかな
lengthAndString longestFirst '1234567';'abcd';'123456789';'abcdef'
9 123456789
7 1234567
6 abcdef
4 abcd
</syntaxhighlight>
 
=={{header|Java}}==
NB. # y is the tally of items (penultimate dimension) in the array y
<syntaxhighlight lang="java">
# 323 43 5j3
import java.util.ArrayList;
3
import java.util.Comparator;
import java.util.List;
# 'literal (a string)'
</syntaxhighlight>
18
<syntaxhighlight lang="java">
void printCompare(String stringA, String stringB) {
/: 'cbad' NB. index ordering vector (grade up)
if (stringA.length() > stringB.length()) {
2 1 0 3
System.out.printf("%d %s%n", stringA.length(), stringA);
System.out.printf("%d %s%n", stringB.length(), stringB);
;: 'j tokenize a sentence.'
} else {
┌─┬────────┬─┬─────────┐
System.out.printf("%d %s%n", stringB.length(), stringB);
│j│tokenize│a│sentence.│
System.out.printf("%d %s%n", stringA.length(), stringA);
└─┴────────┴─┴─────────┘
}
}
#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
 
void printDescending(String... strings) {
(\: #S:0) ;: A NB. order by grade down
List<String> list = new ArrayList<>(List.of(strings));
┌─────────┬───────┬──────┬────┐
list.sort(Comparator.comparingInt(String::length).reversed());
│123456789│1234567│abcdef│abcd│
for (String string : list)
└─────────┴───────┴──────┴────┘
System.out.printf("%d %s%n", string.length(), string);
}
(;:'length literal') , ((;~ #)&> \: #S:0) ;: A NB. box incompatible types with header
</syntaxhighlight>
┌──────┬─────────┐
<pre>
│length│literal │
4 abcd
├──────┼─────────┤
3 abc
│9 │123456789│
</pre>
├──────┼─────────┤
<pre>
│7 │1234567 │
9 123456789
├──────┼─────────┤
7 1234567
│6 │abcdef │
6 abcdef
├──────┼─────────┤
4 abcd
│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 │
└───┴───────────────┘
</pre>
 
<br />
=={{header|Java}}==
An alternate demonstration
{{Works with| Java | 11 }}
{{Works with| Java | 17 }}
Line 1,442 ⟶ 1,996:
abcdef
abcd
</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
// Simple version
print "Simple version:"
s2 = "This is the first string."
s1 = "This is string number two."
 
if s1.len > s2.len then
print s1.len + ": " + s1
print s2.len + ": " + s2
else
print s2.len + ": " + s2
print s1.len + ": " + s1
end if
 
// Extra credit. More than 2 strings
strings = ["qwerty", "abc", "#FFFFFFFF", "255,255,255,255", "3.14159"]
pairs = []
for string in strings
pairs.push([string, string.len])
end for
// sort by index descending
pairs.sort(1, false)
print
print "Extra credit:"
for pair in pairs
print pair[1] + ": " + pair[0]
end for
</syntaxhighlight>
 
{{out}}
<pre>Simple version:
26: This is string number two.
25: This is the first string.
 
Extra credit:
15: 255,255,255,255
9: #FFFFFFFF
7: 3.14159
6: qwerty
3: abc
</pre>
 
Line 1,846 ⟶ 2,443:
 
=={{header|QB64}}==
 
<syntaxhighlight lang="qb64">
Dim Words(1 To 4) As String
Line 1,905 ⟶ 2,501:
Beneath the pool,
By water cool,
</pre>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
 
(define strings '("abcd" "123456789" "abcdef" "1234567"))
 
(for ([i (sort strings > #:key string-length)])
(printf "'~a' is length ~a~n" i (string-length i)))
</syntaxhighlight>
{{out}}
<pre>
'123456789' is length 9
'1234567' is length 7
'abcdef' is length 6
'abcd' is length 4
</pre>
 
Line 2,007 ⟶ 2,620:
abcd len = 4
done...
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! Code
! Comments
|-
|
≪ " [" OVER SIZE →STR "]" + + +
≫ ''''FormatString'''' STO
'''IF''' OVER SIZE OVER SIZE > '''THEN''' SWAP '''END'''
'''FormatString''' SWAP '''FormatString'''
≫ ''''SRT2S'''' STO
LIST→ → len
≪ len 1 '''FOR''' n
1 n 1 - '''START'''
'''IF''' OVER SIZE OVER SIZE <
'''THEN''' SWAP '''END'''
n ROLLD
'''NEXT'''
n ROLLD
-1 '''STEP'''
1 len '''START''' len ROLL '''FormatString''' '''NEXT'''
≫ ≫ ''''SRTLS'''' STO
|
''( "string" -- "string [length]" )''
''( "s1" "s2" -- "s1 [l1]" "s2 [l2]" )''
Swap strings if necessary
Format strings
''( { strings } -- { strings } )''
Push list in the stack
Use selection sort algorithm (favouring code size to execution time)
Format each string in the stack
|}
The following lines of code deliver what is required:
"AB" "ABCD" '''STR2S'''
{ "ABC" "AB" "ABCD" } '''SRTLS'''
{{out}}
<pre>
5: "ABCD [4]"
4: "AB [2]"
3: "ABCD [4]"
2: "ABC [3]"
1: "AB [2]"
</pre>
 
Line 2,056 ⟶ 2,729:
"e" has length 1 and is the shortest
</pre>
 
=={{header|Scala}}==
{{trans|Java}}
<syntaxhighlight lang="Scala">
object Example extends App {
val strings = Array("abcd", "123456789", "abcdef", "1234567")
compareAndReportStringsLength(strings)
 
def compareAndReportStringsLength(strings: Array[String]): Unit = {
if (strings.nonEmpty) {
val Q = '"'
val hasLength = " has length "
val predicateMax = " and is the longest string"
val predicateMin = " and is the shortest string"
val predicateAve = " and is neither the longest nor the shortest string"
 
val sortedStrings = strings.sortBy(-_.length)
val maxLength = sortedStrings.head.length
val minLength = sortedStrings.last.length
 
sortedStrings.foreach { str =>
val length = str.length
val predicate = length match {
case `maxLength` => predicateMax
case `minLength` => predicateMin
case _ => predicateAve
}
println(s"$Q$str$Q$hasLength$length$predicate")
}
}
}
}
</syntaxhighlight>
{{out}}
<pre>
"123456789" has length 9 and is the longest string
"1234567" has length 7 and is neither the longest nor the shortest string
"abcdef" has length 6 and is neither the longest nor the shortest string
"abcd" has length 4 and is the shortest string
 
</pre>
 
 
=={{header|Transd}}==
Line 2,121 ⟶ 2,836:
 
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.
<syntaxhighlight lang="ecmascriptwren">import "./upc" for Graphemes
 
var printCounts = Fn.new { |s1, s2, c1, c2|
27

edits