Compare length of two strings: Difference between revisions

Add Kotlin
(Add Kotlin)
 
(28 intermediate revisions by 13 users not shown)
Line 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 786 ⟶ 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 806 ⟶ 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 832 ⟶ 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 850 ⟶ 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 1,029 ⟶ 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 1,205 ⟶ 1,254:
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
funcproc stringLengthscmp a$ b$ . .
lineA$if = "\"" &len a$ & "\" (length: " &< len ab$ & ")"
swap a$ b$
lineB$ = "\"" & b$ & "\" (length: " & len b$ & ")"
if len a$ >= len b$
print lineA$ ; print lineB$
else
print lineB$ ; print lineA$
.
print a$ & " - " & len a$
print b$ & " - " & len b$
print ""
.
call stringLengthscmp "Easy" "Language"
call stringLengthscmp "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")
"Language" (length: 8)
"Easy" (length: 4)
"Rosetta" (length: 7)
"Code" (length: 4)
</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, " ") + "charsunits".padStart(6, " ") + "bytes".padStart(6, " "))
for each text value in sorted
writeLine(value.padEnd(15, " ") +
Line 1,241 ⟶ 1,298:
{{out}}
<pre>
text charsunits bytes
مرحبا بالعالم 13 25
Привет, мир 11 20
123456789 9 9
Line 1,521 ⟶ 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,845 ⟶ 1,894:
"shorter😀" has length (codepoints) 8 and utf8 byte length 11.
"longer" has length (codepoints) 6 and utf8 byte length 6.
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
fun main() {
printTwoStrings("a short string", "a fairly long string")
printStringsInDescendingLengthOrder(listOf("abcd", "123456789", "abcdef", "1234567"))
}
 
fun printTwoStrings(a: String, b: String) {
val (shorter, longer) = if (a.length < b.length) Pair(a, b) else Pair(b, a)
println("%3d: %s".format(longer.length, longer))
println("%3d: %s".format(shorter.length, shorter))
}
 
fun printStringsInDescendingLengthOrder(strings: Collection<String>) {
strings.sortedByDescending(String::length).forEach {
println("%3d: %s".format(it.length, it))
}
}
</syntaxhighlight>
{{out}}
<pre>
20: a fairly long string
14: a short string
9: 123456789
7: 1234567
6: abcdef
4: abcd
</pre>
 
Line 1,947 ⟶ 2,025:
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 2,052 ⟶ 2,173:
6 Pascal
6 Foobar</pre>
 
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="pascal">
begin
var (s1,s2) := ('Bye','Hello');
if s1.Length < s2.Length then
Swap(s1,s2);
Println(s1,s1.Length);
Println(s2,s2.Length);
Println;
var strArr := |'wolf','cat','crocodile','tiger'|;
strArr.OrderByDescending(s -> s.Length).PrintLines(s -> $'{s,9} - {s.Length}');
end.
</syntaxhighlight>
{{out}}
<pre>
Hello 5
Bye 3
 
crocodile - 9
tiger - 5
wolf - 4
cat - 3
</pre>
 
=={{header|Perl}}==
Line 2,351 ⟶ 2,496:
 
=={{header|QB64}}==
 
<syntaxhighlight lang="qb64">
Dim Words(1 To 4) As String
Line 2,639 ⟶ 2,783:
</pre>
 
=={{header|TransdScala}}==
{{trans|Java}}
<syntaxhighlight lang="Scheme">#lang transd
<syntaxhighlight lang="Scala">
object Example extends App {
val strings = Array("abcd", "123456789", "abcdef", "1234567")
compareAndReportStringsLength(strings)
 
def compareAndReportStringsLength(strings: Array[String]): Unit = {
MainModule: {
if (strings.nonEmpty) {
v: ["abcd","123456789","abcdef","1234567"],
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)
_start: (λ
val maxLength = sortedStrings.head.length
(for s in (sort v (λ l String() r String()
val minLength = sortedStrings.last.length
(ret (< (size r) (size l))))) do
 
(lout width: 10 s " : " (size s) " code points") )
sortedStrings.foreach { str =>
)
val length = str.length
}</syntaxhighlight>
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|Swift}}==
Swift provides a simple ''count'' property to find how many syntactic characters are in any given String. When counting bytes Swift supports Unicode codepoints.
 
In this example we use the ''sorted'' and ''forEach'' methods from the Sequence protocol to first sort our list into a new Array and then print each item in order. String interpolation is used to print the details of each item.
 
Here we use anonymous argument names with the ''sorted'' closure and a named argument with the ''forEach'' to illustrate how to use either style.
<syntaxhighlight lang="Swift">
let list = ["abcd", "abcd🤦‍♂️", "123456789", "abcdef", "1234567"]
list.sorted { $0.count > $1.count }.forEach { string in
print("\(string) has \(string.count) characters")
}
</syntaxhighlight>
{{out}}
<pre>
123456789 :has 9 code pointscharacters
1234567 :has 7 code pointscharacters
abcdef :has 6 code pointscharacters
abcd🤦‍♂️ has 5 characters
abcd : 4 code points
abcd has 4 characters
</pre>
 
Line 2,703 ⟶ 2,889:
 
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|
49

edits