diff --git a/std/strings/compare.jule b/std/strings/compare.jule new file mode 100644 index 000000000..82342e227 --- /dev/null +++ b/std/strings/compare.jule @@ -0,0 +1,33 @@ +// Copyright 2024 The Jule Programming Language. +// Use of this source code is governed by a BSD 3-Clause +// license that can be found in the LICENSE file. + +// Returns an integer comparing two strings lexicographically. +// The result will be 0 if a == b, -1 if a < b, and +1 if a > b. +// +// Use compare when you need to perform a three-way comparison (with +// [slices::SortFunc], for example). It is usually clearer and always faster +// to use the built-in string comparison operators ==, <, >, and so on. +fn Compare(a: str, b: str): int { + mut l := len(a) + if len(b) < l { + l = len(b) + } + mut i := 0 + for i < l; i++ { + c1, c2 := a[i], b[i] + if c1 < c2 { + ret -1 + } + if c1 > c2 { + ret +1 + } + } + if len(a) < len(b) { + ret -1 + } + if len(a) > len(b) { + ret +1 + } + ret 0 +} \ No newline at end of file