Compare length of two strings: Difference between revisions
Add Kotlin
No edit summary |
(Add Kotlin) |
||
(31 intermediate revisions by 13 users not shown) | |||
Line 723:
call comp("abcd", "123456789")</syntaxhighlight>
==={{header|
{{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">
void WriteSorted(string[] strings)
{
var sorted = strings.OrderByDescending(x => x.Length);
foreach(var s in sorted) Console.WriteLine($"{s.Length}: {s}");
}
WriteSorted(new string[] { "abcd", "123456789", "abcdef", "1234567" });
</syntaxhighlight>
{{output}}
<pre>
9: 123456789
7: 1234567
6: abcdef
4: abcd
</pre>
Line 1,205 ⟶ 1,254:
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
swap a$ b$
.
print a$ & " - " & len a$
print b$ & " - " & len b$
print ""
.
</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,496 ⟶ 1,577:
=={{header|J}}==
<syntaxhighlight lang=J>
NB. solution
chars=: 9&u:@>
longestFirst=: \: #@chars
lengthAndString=: ([:":@,.#@chars),.' ',.chars
NB. `Haruno-umi Hinemosu-Notari Notarikana'
NB. Spring ocean ; Swaying gently ; All day long.
7 ひねもすのたり
lengthAndString longestFirst '1234567';'abcd';'123456789';'abcdef'
9 123456789
7 1234567
6 abcdef
4 abcd
</syntaxhighlight>
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
</syntaxhighlight>
<syntaxhighlight lang="java">
void printCompare(String stringA, String stringB) {
if (stringA.length() > stringB.length()) {
System.out.printf("%d %s%n", stringA.length(), stringA);
System.out.printf("%d %s%n", stringB.length(), stringB);
} else {
System.out.printf("%d %s%n", stringB.length(), stringB);
System.out.printf("%d %s%n", stringA.length(), stringA);
}
}
void printDescending(String... strings) {
List<String> list = new ArrayList<>(List.of(strings));
list.sort(Comparator.comparingInt(String::length).reversed());
for (String string : list)
System.out.printf("%d %s%n", string.length(), string);
}
</syntaxhighlight>
<pre>
4 abcd
3 abc
</pre>
<pre>
9 123456789
7 1234567
6 abcdef
4 abcd
</pre>
<br />
An alternate demonstration
{{Works with| Java | 11 }}
{{Works with| Java | 17 }}
Line 1,820 ⟶ 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,922 ⟶ 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,027 ⟶ 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,326 ⟶ 2,496:
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
Dim Words(1 To 4) As String
Line 2,614 ⟶ 2,783:
</pre>
=={{header|
{{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|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>
abcd🤦♂️ has 5 characters
abcd has 4 characters
</pre>
Line 2,678 ⟶ 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="
var printCounts = Fn.new { |s1, s2, c1, c2|
|