JavaScript 中比较字符串的最佳方法?
我正在尝试优化一个在 JavaScript 中对字符串进行二分搜索的函数。
二分查找要求您知道键是==
枢轴还是<
枢轴。
但这需要在 JavaScript 中进行两次字符串比较,这与类 C
语言的 strcmp()
函数不同,该函数返回三个值 (-1, 0, +1 )
表示(小于、等于、大于)。
JavaScript 中是否有这样的本机函数,可以返回三元值,以便在二分搜索的每次迭代中只需要一次比较?
I am trying to optimize a function which does binary search of strings in 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).
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
localeCompare()
方法。进一步阅读:
You can use the
localeCompare()
method.Further Reading:
在 JavaScript 中,您可以检查两个字符串是否具有与整数相同的值,因此可以执行以下操作:
"A"
"A"
"A"
"A"
"A"
“B”
“A”==“B”
“A”> "B"
因此,您可以创建自己的函数,以与
strcmp()
相同的方式检查字符串。所以这将是执行相同操作的函数:
Well in JavaScript you can check two strings for values same as integers so yo can do this:
"A" < "B"
"A" == "B"
"A" > "B"
And therefore you can make your own function that checks strings the same way as the
strcmp()
.So this would be the function that does the same:
您可以使用比较运算符来比较字符串。
strcmp
函数可以这样定义:Edit 这是一个字符串比较函数,最多需要 min { length(a< /em>), length(b) } 比较来了解两个字符串如何相互关联:
You can use the comparison operators to compare strings. A
strcmp
function could be defined like this: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: