比较 Intersystems Cache Objectscript 中的字符串

Compare strings in Intersystems Cache Objectscript

给定:

2 个字符串 strA、strB

我要:

在 Intersystems Cache ObjectScript 中对它们与 return <0、=0 或 >0 进行比较。

到目前为止:

我在文档中找到了满足我需求的功能StrComp。不幸的是,这个函数不是 Cache ObjectScript 的一部分,而是来自 Caché Basic。

我已将函数包装为 class实用程序的方法 class:

ClassMethod StrComp(
    pstrElem1 As %String,
    pstrElem2 As %String) As %Integer [ Language = basic ]
{
    Return StrComp(pstrElem1,pstrElem2)
}

是否推荐这种方法? 有什么功能可用吗?

提前致谢。

可以在您的代码中使用不同的语言,如果它能解决您的任务,为什么不呢。但您必须注意,并非所有语言都适用于服务器端。 JavaScript仍然是客户端语言,不能这样使用

有点不清楚您希望此字符串比较做什么,但您似乎正在寻找 follows ]sorts after ]] 运算符。

文档(取自here):

  • 二进制跟随运算符 (]) 测试左操作数中的字符是否在 ASCII 整理序列中位于右操作数中的字符之后。
  • 运算符后二进制排序(]])测试左操作数是否在数字下标排序序列中的右操作数之后排序。

语法看起来很奇怪,但它应该可以满足您的需要。

if "apple" ] "banana" ...
if "apple" ]] "banana" ...

如果你想要纯 ObjectScript,你可以使用它;它假设你真的想做类似 Java 的 Comparable<String>:

///
/// Compare two strings as per a Comparator<String> in Java
///
/// This method will only do _character_ comparison; and it pretty much
/// assumes that your Caché installation is Unicode.
///
/// This means that no collation order will be taken into account etc.
///
/// @param o1: first string to compare
/// @param o2: second string to compare
/// @returns an integer which is positive, 0 or negative depending on
/// whether o1 is considered lexicographically greater than, equal or
/// less than o2
ClassMethod strcmp(o1 as %String, o2 as %String) as %Integer
{
    #dim len as %Integer
    #dim len2 as %Integer
    set len = $length(o1)
    set len2 = $length(o2)
    /*
     * Here we rely on the particularity of $ascii to return -1 for any
     * index asked within a string literal which is greater than it length.
     *
     * For instance, $ascii("x", 2) will return -1.
     *
     * Please note that this behavior IS NOT documented!
     */
    if (len2 > len) {
        len = len2
    }

    #dim c1 as %Integer
    #dim c2 as %Integer

    for index=1:1:len {
        set c1 = $ascii(o1, index)
        set c2 = $ascii(o2, index)

        if (c1 '= c2) {
            return c1 - c2
        }
    }

    /*
     * The only way we could get here is if both strings have the same
     * number of characters (UTF-16 code units, really) and are of
     * equal length
     */
    return 0
}