代码之家  ›  专栏  ›  技术社区  ›  HRJ

比较javascript中字符串的最佳方法?[副本]

  •  346
  • HRJ  · 技术社区  · 15 年前

    这个问题已经有了答案:

    我正在尝试优化一个函数,它在javascript中对字符串进行二进制搜索。

    二进制搜索要求您知道密钥是否 == 枢轴或 < 枢轴。

    但这需要在javascript中进行两个字符串比较,而不像在 C 就像语言 strcmp() 返回三个值的函数 (-1, 0, +1) 用于(小于、等于、大于)。

    javascript中是否有这样一个本地函数,它可以返回三元值,以便在每次二进制搜索迭代中只需要一个比较?

    3 回复  |  直到 6 年前
        1
  •  467
  •   Lee Goddard    6 年前

    你可以使用 localeCompare() 方法。

    string_a.localeCompare(string_b);
    
    /* Expected Returns:
    
     0:  exact match
    
    -1:  string_a < string_b
    
     1:  string_a > string_b
    
     */
    

    进一步阅读:

        2
  •  52
  •   Cipi    10 年前

    在javascript中,您可以检查两个字符串的值是否与整数相同,所以您可以这样做:

    • "A" < "B"
    • "A" == "B"
    • "A" > "B"

    因此,您可以使用与 strcmp() .

    所以这个函数的作用是一样的:

    function strcmp(a, b)
    {   
        return (a<b?-1:(a>b?1:0));  
    }
    
        3
  •  13
  •   Gumbo    15 年前

    你可以 use the comparison operators to compare strings . 一 strcmp 可以这样定义函数:

    function strcmp(a, b) {
        if (a.toString() < b.toString()) return -1;
        if (a.toString() > b.toString()) return 1;
        return 0;
    }
    

    编辑 _____s a string comparison function that takes at most ming_length( (长度) )}比较两个字符串之间的关系:

    function strcmp(a, b) {
        a = a.toString(), b = b.toString();
        for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
        if (i === n) return 0;
        return a.charAt(i) > b.charAt(i) ? -1 : 1;
    }