Compare length of two strings: Difference between revisions
m
syntax highlighting fixup automation
(PL/I code added) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 18:
=={{header|Ada}}==
<
procedure compare_lengths is
package string_vector is new ada.containers.indefinite_vectors
Line 39:
end loop;
end compare_lengths;
</syntaxhighlight>
{{out}}
./compare_lengths Like sands through the hourglass these are the days of our lives
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>
In most Algol 68 implementations such as Algol 68G and Rutgers Algol 68, the CHAR type is an 8-bit byte.
<
# returns the length of s using the builtin UPB and LWB operators #
OP LENGTH = ( STRING s )INT: ( UPB s + 1 ) - LWB s;
Line 71:
print string( not shorter );
IF LENGTH shorter <= LENGTH not shorter THEN print string( shorter ) FI
END</
{{out}}
<pre>
Line 80:
=={{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]
<syntaxhighlight lang="apl">
sv ← 'defg' 'hijklm' 'abc' 'abcd'
⍉(⍴¨sv[⍒sv]),[0.5]sv[⍒sv]
Line 87:
4 abcd
3 abc
</syntaxhighlight>
=={{header|Arturo}}==
<
map sort.descending.by:'v
map strs 'str -> #[s: str, v: size str]
Line 112:
]
print ["sorted strings (by length):" sortByLength ["abcd" "123456789" "abcdef" "1234567"]]</
{{out}}
Line 120:
=={{header|Asymptote}}==
<
void comp(string A, string B) {
Line 132:
}
comp("abcd", "123456789");</
{{out}}
<pre>123456789 9
Line 138:
=={{header|AutoHotkey}}==
<
sorted := []
Line 156:
}
}
MsgBox % result</
{{out}}
<pre>"123456789" has length 9 and is the longest string.
Line 164:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f COMPARE_LENGTH_OF_TWO_STRINGS.AWK
BEGIN {
Line 185:
}
}
</syntaxhighlight>
{{out}}
<pre>
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.
<
•Show Compare ⟨"hello", "person"⟩
•Show Compare ⟨"abcd", "123456789", "abcdef", "1234567"⟩</
<syntaxhighlight lang="text">┌─
╵ 6 "person"
5 "hello"
Line 217:
6 "abcdef"
4 "abcd"
┘</
=={{header|C}}==
{{Works with|C11}}
<
#include <stdlib.h>
#include <string.h>
Line 283:
return EXIT_SUCCESS;
}</
{{output}}
<pre>
Line 293:
=={{header|C++}}==
<
#include <algorithm>
#include <string>
Line 342:
return EXIT_SUCCESS;
}</
{{output}}
Line 351:
</pre>
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
Line 399:
}
}
</syntaxhighlight>
{{output}}
Line 409:
=={{header|CFEngine}}==
<
bundle agent __main__
{
Line 424:
"'$(sorted[$(sort_idx)])' is $(sort_idx) characters in length.";
}
</syntaxhighlight>
{{output}}
Line 460:
{{works with|Commodore BASIC|2.0}}
{{works with|Commodore BASIC|3.5}}
<
1 REM COMPARE LENGTH OF TWO STRINGS
2 REM GIVEN TWO STRINGS OF DIFFERENT
Line 515:
1080 DATA "I LIKE TEA"
1090 DATA "WE SEE THEM EVERY WEEK"
1100 DATA "$$$"</
{{out}}
Line 539:
==={{header|BASIC256}}===
<
if length(A$) >= length(B$) then
print A$, length(A$)
Line 549:
end subroutine
call comp("abcd", "123456789")</
==={{header|PureBasic}}===
<
If Len(A) >= Len(B)
PrintN(A + #TAB$ + Str(Len(A)))
Line 565:
comp("abcd", "123456789")
Input()
CloseConsole()</
==={{header|QBasic}}===
Line 571:
{{works with|QuickBasic|4.5}}
{{works with|True BASIC}}
<
IF LEN(A$) >= LEN(B$) THEN
PRINT A$, LEN(A$)
Line 582:
CALL comp("abcd", "123456789")
END</
==={{header|Run BASIC}}===
<
if len(A$) >= len(B$) then
print A$; chr$(9); len(A$)
Line 595:
end sub
call comp "abcd", "123456789"</
==={{header|True BASIC}}===
{{works with|QBasic}}
<
IF LEN(A$) >= LEN(B$) THEN
PRINT A$, LEN(A$)
Line 610:
CALL comp("abcd", "123456789")
END</
{{out}}
<pre>Igual que la entrada de FreeBASIC.
Line 616:
==={{header|Yabasic}}===
<
if len(A$) >= len(B$) then
print A$, chr$(9), len(A$)
Line 626:
end sub
comp("abcd", "123456789")</
==={{header|FreeBASIC}}===
<
if len(A)>=len(B) then
print A, len(A)
Line 639:
end sub
comp( "abcd", "123456789" )</
{{out}}<pre>123456789 9
abcd 4</pre>
Line 647:
remain self-contained, created (a very inefficient) sort_int()
procedure.
<
program demo_sort_indexed
implicit none
Line 673:
end program demo_sort_indexed
</syntaxhighlight>
{{out}}
<pre>
Line 697:
=={{header|FutureBasic}}==
<
NSComparisonResult result = NSOrderedDescending
if len(obj1) >= len(obj2) then result = NSOrderedAscending
Line 727:
fn DoIt
HandleEvents</
Output:
Line 739:
=={{header|Go}}==
{{works with|Go|1.8+}}
<
import (
Line 769:
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 [https://pkg.go.dev/sort?utm_source=gopls#SliceStable SliceStable]
<
return len(strings[i]) > len(strings[j])
}
sort.SliceStable(strings, comparisonFunction)</
{{output}}
.\main.exe
Line 794:
=={{header|Harbour}}==
We can, easily, realize this task with Harbour, utilizing its strong array-handling set of functions.
<
PROCEDURE Main()
Line 820:
hb_strFormat( "(length = %d chars)", Len(e) ) ) } )
RETURN NIL
</syntaxhighlight>
Output:
<pre>
Line 845:
=={{header|Haskell}}==
Using native String type:
<
let strs = if length s1 > length s2 then [s1, s2] else [s2, s1]
mapM_ (\s -> putStrLn $ show (length s) ++ "\t" ++ show s) strs</
<pre>λ> task "short string" "longer string"
Line 860:
or more practically useful Text:
<
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</
<pre>λ> :set -XOverloadedStrings
Line 938:
{{Works with| Java | 11 }}
{{Works with| Java | 17 }}
<
import java.io.PrintStream;
Line 991:
}
}
}</
{{output}}
Line 1,001:
=={{header|JavaScript}}==
JavaScript (ECMA Script) file stringlensort.js.
<
* Compare and report strings lengths.
*
Line 1,068:
document.getElementById("input").value = "abcd\n123456789\nabcdef\n1234567";
compareStringsLength(input, output);</
HTML file (with embeded CSS) to run the script.
<
<head>
Line 1,116:
</body>
</html></
{{Output}}
<pre>"123456789" has length 9 and is the longest string
Line 1,130:
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:
<
println("Position Char Bytes\n==============================")
for (i, c) in enumerate(s)
println("$i $c $(sizeof(c))")
end
</
<pre>
Position Char Bytes
Line 1,150:
one byte, an error is thrown for bad indexing. This can be demonstrated by casting
the above string to codeunits:
<
for (i, c) in enumerate(codeunits(s))
println("$i $(string(c, base=16)) $(sizeof(c))")
end
</
<pre>
Position Codeunit Bytes
Line 1,168:
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'
</syntaxhighlight>
So, whether a string is longer or shorter depends on the encoding, as below:
<
length(codeunits("ñññ")) > length(codeunits("nnnn")) # true as well
</syntaxhighlight>
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<syntaxhighlight lang="jq">
def s1: "longer";
def s2: "shorter😀";
Line 1,191:
| "\"\(.)\" has length (codepoints) \(length) and utf8 byte length \(utf8bytelength)."
</syntaxhighlight>
{{out}}
<pre>
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.
<syntaxhighlight lang="scheme">
{def L.new
{lambda {:s}
Line 1,217:
{L.disp {P.right :l}}}}}
-> L.disp
</syntaxhighlight>
For instance
<syntaxhighlight lang="scheme">
{def B {L.new abcd 123456789 abcdef 1234567}}
-> B
Line 1,231:
6 : abcdef
7 : 1234567
</syntaxhighlight>
Then we define the L.sort function waiting for a predicate function and a list.
<syntaxhighlight lang="scheme">
{def L.sort
{lambda {:filter :l}
Line 1,253:
{L.insert :x :filter {P.right :l}}}}}}}
-> L.insert
</syntaxhighlight>
Using the following predicate function (which could be anonymous) testing the length of 2 words
<syntaxhighlight lang="scheme">
{def filter
{lambda {:a :b}
{> {W.length :a} {W.length :b}}}}
-> filter
</syntaxhighlight>
we display the B list sorted according to the length of its elements.
<syntaxhighlight lang="scheme">
{L.disp {L.sort filter {B}}}
->
Line 1,273:
6 : abcdef
4 : abcd
</syntaxhighlight>
Note that in lambdatalk words (and numbers) don't need to be quoted.
=={{header|Lua}}==
<
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"}</
{{out}}
<pre>9 123456789
Line 1,290:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Reverse@SortBy[list, StringLength] // TableForm</
{{out}}<pre>
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.
<
const
Line 1,313:
echo &"“{S2}”, byte length = {S2.len}, code points: {S2.toRunes.len}"
echo &"“{S1}”, byte length = {S1.len}, code points: {S1.toRunes.len}"</
{{out}}
Line 1,321:
=={{header|Pascal}}==
{{works with|Extended Pascal}}
<
const
Line 1,383:
analyzeLengths;
printSortedByLengths
end.</
{{out}}
<pre> 11 RosettaCode
Line 1,391:
=={{header|Perl}}==
<
use strict; # https://rosettacode.org/wiki/Compare_length_of_two_strings
Line 1,401:
printf "length %d: %s\n", length(), $_
for sort { length $b <=> length $a } split;
}</
{{out}}
<pre>
Line 1,418:
=={{header|Phix}}==
Lengths are in bytes, for codepoints use length(utf8_to_utf32()) or similar.
<!--<
<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>
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: #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>
<!--</
{{out}}
<pre>
Line 1,434:
=={{header|PHP}}==
<syntaxhighlight lang="php">
<?php
Line 1,535:
</body>
</html></
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
declare (S1, S2) character (20) varying; /* 11 Aug 2022 */
get (S1, S2);
Line 1,545:
else
put (length(S2), S2);
</syntaxhighlight>
=={{header|Python}}==
===Naive solution===
{{works with | Python | 3.8}}
<
B = 'I am string too'
Line 1,561:
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}}
<pre>
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.
<syntaxhighlight lang="python">"""
An example code for the task "Compare length of two strings" (Rosseta Code).
Line 1,655:
compare_and_report_length(*LIST)
print()
</syntaxhighlight>
{{out}}
Line 1,674:
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
Dim Words(1 To 4) As String
Dim Lengths As Integer, Index As Integer, Position As Integer, Done As String, Index2 As Integer
Line 1,696:
Print Words(Position), Len(Words(Position))
Next Index2
</syntaxhighlight>
=={{header|Quackery}}==
<
$ "A slightly longer string of"
Line 1,717:
sortwith [ size dip size < ]
witheach [ echo$ cr ] </
{{out}}
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.
<syntaxhighlight lang="raku"
say "$_: characters:{.chars}, Unicode code points:{.codes}, UTF-8 bytes:{.encode('UTF8').bytes}, UTF-16 bytes:{.encode('UTF16').bytes}" for <👨👩👧👦 BOGUS! 🤔🇺🇸>.sort: -*.chars;</
{{out}}
<pre>Strings (👨👩👧👦, 🤔🇺🇸, BOGUS!) sorted: "longest" first:
Line 1,748:
=={{header|REXX}}==
<
list = '"abcd","123456789","abcdef","1234567"'
Do i=1 By 1 While list>''
Line 1,772:
o:
Say length(arg(1)) arg(1)
Return</
{{out}}
<pre>9 123456789
Line 1,781:
=={{header|Ring}}==
===Two strings===
<
see "working..." + nl
Line 1,796:
see "" + first + " len = " + len(first) + nl + second + " len = " + len(second) + nl
see "done..." + nl
</syntaxhighlight>
{{out}}
<pre>
Line 1,806:
</pre>
===More than two strings===
<
see "working..." + nl
Line 1,824:
next
see "done..." + nl
</syntaxhighlight>
{{out}}
<pre>
Line 1,837:
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
a, b = "Given two strings", "of different length"
[a,b].sort_by{|s| - s.size }.each{|s| puts s + " (size: #{s.size})"}
Line 1,843:
list = ["abcd","123456789","abcdef","1234567"]
puts list.sort_by{|s|- s.size}
</syntaxhighlight>
{{out}}
<pre>of different length (size: 19)
Line 1,853:
=={{header|Rust}}==
<syntaxhighlight lang="rust">
fn compare_and_report<T: ToString>(string1: T, string2: T) -> String {
let strings = [string1.to_string(), string2.to_string()];
Line 1,871:
println!("\n{}", compare_and_report("f", "gh"));
}
</syntaxhighlight>
{{out}}
Line 1,885:
=={{header|Vlang}}==
<
// Tectonics: v run compare-length-of-two-strings.v
module main
Line 1,905:
println("${strs[i]}: with length ${strs[i].len}")
}
}</
{{out}}
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.
<
var printCounts = Fn.new { |s1, s2, c1, c2|
Line 1,967:
System.write("Sorting in descending order by length in codepoints:\n%(list) -> ")
list.sort { |a, b| a.count > b.count }
System.print(list)</
{{out}}
Line 2,000:
=={{header|XPL0}}==
<
func StrLen(A); \Return number of characters in an ASCIIZ string
Line 2,021:
List(SN, 0):= 0; \truncate largest string
];
]</
{{out}}
Line 2,032:
=={{header|Z80 Assembly}}==
<
PrintChar equ &BB5A ;Amstrad CPC BIOS call, prints accumulator to screen as an ASCII character.
Line 2,155:
add a,&F0
adc a,&40 ;This sequence converts a 4-bit hex digit to its ASCII equivalent.
jp PrintChar</
{{out}}
|