JavaScript 相当于 C strncmp(比较字符串长度)
JavaScript 中是否有与 C 函数 strncmp
等效的函数? strncmp
接受两个字符串参数和一个整数length
参数。它会比较两个字符串最多 length
个字符,并确定它们是否相等 length
。
JavaScript 是否有等效的内置函数?
Is there an equivalent in JavaScript to the C function strncmp
? strncmp
takes two string arguments and an integer length
argument. It would compare the two strings for up to length
chars and determine if they were equal as far as length
went.
Does JavaScript have an equivalent built in function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以轻松构建该函数:
函数末尾三元的替代方案可以是
localeCompare
方法,例如return str1.localeCompare(str2);
You could easily build that function:
An alternative to the ternary at the end of the function could be the
localeCompare
method e.greturn str1.localeCompare(str2);
事实并非如此。您可以将其定义为:
It does not. You could define one as:
自 ECMAScript 2015 以来,有
startsWith()
:这涵盖了非常常见的用例,其中比较的长度是
searchString
的长度,并且只需要一个布尔返回值(strcmp( )
返回一个整数来指示相对顺序。)Mozilla 文档页面 还包含一个 polyfill 用于 <代码>String.prototype.startsWith()。
Since ECMAScript 2015 there is
startsWith()
:This covers the very frequent use case where the length of the comparison is the length of the
searchString
, and only a boolean return value is required (strcmp()
returns an integer to indicate relative order, instead.)The Mozilla doc page also contains a polyfill for
String.prototype.startsWith()
.没有,但您可以在此处找到一个,以及许多其他有用的 JavaScript 函数。
It doesn't but you can find one here, along with many other useful javascript functions.
您始终可以先对字符串进行子串,然后进行比较。
you could always substring the strings first, and then compare.