Compare length of two strings: Difference between revisions

Added solution for Go
(Added solution for Go)
Line 737:
abcdef 6
abcd 4</pre>
=={{header|Go}}==
{{works with|Go|1.8+}}
<lang go>package main
 
import (
"fmt"
"os"
"sort"
)
 
func main() {
// If no command-line arguments are specified when running the program, use example data
if len(os.Args) == 1 {
compareStrings("abcd", "123456789", "abcdef", "1234567")
} else {
// First argument, os.Args[0], is program name. Command-line arguments start from 1
strings := os.Args[1:]
compareStrings(strings...)
}
}
 
// Variadic function that takes any number of string arguments for comparison
func compareStrings(strings ...string) {
// "strings" slice is sorted in place
// sort.SliceStable keeps strings in their original order when elements are of equal length (unlike sort.Slice)
sort.SliceStable(strings, func(i, j int) bool {
return len(strings[i]) > len(strings[j])
})
 
for _, s := range strings {
fmt.Printf("%d: %s\n", len(s), s)
}
}</lang>
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]
<lang go>comparisonFunction := func(i, j int) bool {
return len(strings[i]) > len(strings[j])
}
 
sort.SliceStable(strings, comparisonFunction)</lang>
{{output}}
.\main.exe
<pre>9: 123456789
7: 1234567
6: abcdef
4: abcd</pre>
.\main.exe The quick brown fox jumps over the lazy dog
<pre>5: quick
5: brown
5: jumps
4: over
4: lazy
3: The
3: fox
3: the
3: dog</pre>
=={{header|Harbour}}==
We can, easily, realize this task with Harbour, utilizing its strong array-handling set of functions.