From a50176d502c10f92ff50ffbaf82bb9510ecc7d8e Mon Sep 17 00:00:00 2001 From: mertcandav Date: Mon, 2 Sep 2024 18:18:39 +0300 Subject: [PATCH] std::strings:: add the Compare function --- std/strings/compare.jule | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 std/strings/compare.jule 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