在JavaScript中比较字符串的最佳方法? [重复]

本文翻译自:Optimum way to compare strings in JavaScript? [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

I am trying to optimize a function which does binary search of strings in JavaScript. 我正在尝试优化一个在JavaScript中对字符串进行二进制搜索的函数。

Binary search requires you to know whether the key is == the pivot or < the pivot. 二进制搜索要求您知道密钥是==枢轴还是<枢轴。

But this requires two string comparisons in JavaScript, unlike in C like languages which have the strcmp() function that returns three values (-1, 0, +1) for (less than, equal, greater than). 但这需要在JavaScript中进行两次字符串比较,这与C语言类似,后者的strcmp()函数返回三个值(-1, 0, +1) (小于,等于,大于)。

Is there such a native function in JavaScript, that can return a ternary value so that just one comparison is required in each iteration of the binary search? JavaScript中是否存在这样的本机函数,它可以返回三元值,以便在二进制搜索的每次迭代中只需要进行一次比较?


#1楼

参考:https://stackoom.com/question/95tK/在JavaScript中比较字符串的最佳方法-重复


#2楼

You can use the localeCompare() method. 您可以使用localeCompare()方法。

string_a.localeCompare(string_b);

/* Expected Returns:

 0:  exact match

-1:  string_a < string_b

 1:  string_a > string_b

 */

Further Reading: 进一步阅读:


#3楼

You can use the comparison operators to compare strings . 您可以使用比较运算符来比较字符串 A strcmp function could be defined like this: strcmp函数可以像这样定义:

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

Edit Here's a string comparison function that takes at most min { length( a ), length( b ) } comparisons to tell how two strings relate to each other: 编辑这是一个字符串比较函数,它最多需要min {length( a ),length( b )}比较,以告诉两个字符串如何相互关联:

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;
}

#4楼

Well in JavaScript you can check two strings for values same as integers so yo can do this: 在JavaScript中你可以检查两个字符串的值与整数相同,所以你可以这样做:

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

And therefore you can make your own function that checks strings the same way as the strcmp() . 因此,您可以创建自己的函数,以与strcmp()相同的方式检查字符串。

So this would be the function that does the same: 所以这将是相同的功能:

function strcmp(a, b)
{   
    return (a<b?-1:(a>b?1:0));  
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值