Compare length of two strings: Difference between revisions

m
Reverted edits by Anonymous31415927 (talk) to last revision by Absayuti
m (Reverted edits by Anonymous31415927 (talk) to last revision by Absayuti)
Line 36:
"short" has length: 5 bytes.
</pre>
 
=={{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]
<lang APL>
sv ← 'defg' 'hijklm' 'abc' 'abcd'
⍉(⍴¨sv[⍒sv]),[0.5]sv[⍒sv]
6 hijklm
4 defg
4 abcd
3 abc
</lang>
 
=={{header|AutoHotkey}}==
<lang 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</lang>
{{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 shorted string.</pre>
 
=={{header|AWK}}==
<lang 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)
}
}
</lang>
{{out}}
<pre>
a<b
9 123456789
4 abcd
 
a>b
6 longer
5 short
 
a=b
5 world
5 hello
</pre>
 
=={{header|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.
 
<lang bqn>Compare ← >·(⍒⊑¨)⊸⊏≠⊸⋈¨
 
•Show Compare ⟨"hello", "person"⟩
•Show Compare ⟨"abcd", "123456789", "abcdef", "1234567"⟩</lang>
<lang>┌─
╵ 6 "person"
5 "hello"
┌─
╵ 9 "123456789"
7 "1234567"
6 "abcdef"
4 "abcd"
┘</lang>
 
=={{header|C}}==
Line 168 ⟶ 261:
"abcd" has length 4 and is the shortest string
</pre>
=={{header|C sharp|C#}}==
<lang csharp>using System;
using System.Collections.Generic;
Line 226 ⟶ 319:
</pre>
 
=={{header|FreeBASICBASIC}}==
==={{header|Commodore BASIC}}===
{{works with|Commodore BASIC|2.0}}
{{works with|Commodore BASIC|3.5}}
<lang gwbasic>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 "$$$"</lang>
 
{{out}}
<pre>
*** (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 )
</pre>
 
==={{header|FreeBASIC}}===
<lang freebasic>sub comp( A as string, B as string )
if len(A)>=len(B) then
Line 268 ⟶ 443:
13 "longer string"
12 "short string"</pre>
 
=={{header|J}}==
<pre>
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 │
└───┴───────────────┘
</pre>
 
=={{header|Java}}==
Line 332 ⟶ 571:
"abcdef" has length 6 and is neither the longest nor the shortest string
"abcd" has length 4 and is the shortest string</pre>
 
=={{header|JavaScript}}==
<lang JavaScript>// 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 lengths 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);
</lang>
<lang html><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>
Output:<br>
<textarea rows="20" cols="80" id="output"></textarea>
</form>
</main>
<script src="stringlensort.js"></script>
</body>
 
</html>
</lang>
 
=={{header|Julia}}==
Line 524 ⟶ 645:
"shorter😀" has length (codepoints) 8 and utf8 byte length 11.
"longer" has length (codepoints) 6 and utf8 byte length 6.
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>list = {"abcd", "123456789", "abcdef", "1234567"};
Reverse@SortBy[list, StringLength] // TableForm</lang>
 
{{out}}<pre>
123456789
1234567
abcdef
abcd
</pre>
 
Line 615 ⟶ 746:
6 Pascal
6 Foobar</pre>
 
=={{header|Perl}}==
<lang 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;
}</lang>
{{out}}
<pre>
 
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
</pre>
 
=={{header|Phix}}==
Line 824 ⟶ 981:
done...
</pre>
 
=={{header|Vlang}}==
<lang go>// 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}")
}
}</lang>
 
{{out}}
<pre>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</pre>
 
=={{header|Wren}}==
Line 903 ⟶ 1,095:
Sorting in descending order by length in codepoints:
[abcd, 123456789, abcdef, 1234567] -> [123456789, 1234567, abcdef, abcd]
</pre>
 
=={{header|XPL0}}==
<lang 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
];
]</lang>
 
{{out}}
<pre>
123456789 length is 9
1234567 length is 7
abcdef length is 6
abcd length is 4
</pre>
 
10,333

edits