Home > php教程 > php手册 > PHP strcmp,strnatcmp,strncmp函数的区别,strnatcmpstrncmp

PHP strcmp,strnatcmp,strncmp函数的区别,strnatcmpstrncmp

WBOY
Release: 2016-06-13 09:24:32
Original
1578 people have browsed it

PHP strcmp,strnatcmp,strncmp函数的区别,strnatcmpstrncmp

字符串比较说明
当s1
当s1=s2时,返回值= 0
当s1>s2时,返回正数

<span> 1</span> <?<span>php
</span><span> 2</span> <span>$str1</span> = 'str100'<span>;
</span><span> 3</span> <span>$str2</span> = 'str20'<span>;
</span><span> 4</span> <span>echo</span> <span>strcmp</span>(<span>$str1</span>, <span>$str2</span>)."<br>"<span>;
</span><span> 5</span> <span>//输出</span><span>-1</span>
<span> 6</span> <span>echo</span> <span>strnatcmp</span>(<span>$str1</span>, <span>$str2</span>)."<br>"<span>;
</span><span> 7</span> <span>//输出</span><span>1</span>
<span> 8</span> <span>echo</span> <span>strncmp</span>(<span>$str1</span>, <span>$str2</span>, 5)."<br>"<span>;
</span><span> 9</span> <span>//输出</span><span>-1</span>
<span>10</span> 
<span>11</span> ?>
Copy after login

strcmp(str1, str2)函数按照字符比较两个字符串,即两个字符串自左向右逐个字符比较(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止。如:"A""A" "computer">"compare"

strnatcmp(str1, str2)函数使用自然排序算法比较字符串该函数实现了以人类习惯对数字型字符串进行排序的比较算法,这就是“自然顺序”。

strncmp(str1, str2, len)函数比较的原理参照strcmp(str1, str2)函数,区别在于只是比较字符串的开头的len个字符。

ps:以上三个函数都是区分大小写的,若是对比较的字符串不区分大小写,则有另外三个类似函数:strcasecmp,strnatcasecmp,strncasecmp.

字符串比较函数strcmp()与strncmp()

比较一下:
函数原型:extern int strcmp(const char *s1,const char * s2);
int strncmp(char *str1, char *str2, int maxlen);
可以看出strncmp多一个参数maxlen,区别就在这里,这个表示的是比较字符串的前maxlen长度的字符

两者返回值也不同:
strcmp,当s1 当s1==s2时,返回0
当s1>s2时,返回正数
strncmp:如果前maxlen字节完全相等,返回值就=0;
如果在前maxlen字节比较过程中,出现str1[n]与str2[n]不等,则返回(str1[n]-str2[n])。
 

字符串比较函数strcmp()与strncmp()

函数:int strcmp (const char *s1, const char *s2)
这个函数用来比较s1和s2字符串,这个函数将返回一个值,它的符号与第一对不同的字符的比较结果相关。
如果两个字符串相等的话,strcmp将返回0。
如果s1是s2的一个子串的话,s1小于s2
此外还有函数
int strncmp (const char *s1, const char *s2, size_t size)
此函数与strcmp极为类似。不同之处是,strncmp函数是指定比较size个字符。也就是说,如果字符串s1与s2的前size个字符相同,函数返回值为0。
 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template