Home  >  Article  >  Backend Development  >  PHP function strncmp() for string comparison of the first n characters (case sensitive)

PHP function strncmp() for string comparison of the first n characters (case sensitive)

黄舟
黄舟Original
2017-11-04 13:35:282177browse

Example

Compare two strings (case sensitive):

<?php
echo strncmp("Hello world!","Hello earth!",6);
?>

Definition and usage

strncmp() Function Compare two strings (case sensitive).

Note: strncmp() is binary safe and case-sensitive.

Tips: This function is similar to the strcmp() function, except that strcmp() does not have a length parameter.

Syntax

strncmp(string1,string2,length)
Parameters Description
string1 Required. Specifies the first string to compare.
string2 Required. Specifies the second string to be compared.
length Required. Specifies the number of characters per string used for comparison.

Technical details

##PHP version: More Multiple instances
Return value: This function returns:
  • 0 - if the two strings are equal

  • ##8f029751ac12f19769820fc6523b37120 - if string1 Greater than string2

4+

Example 1

Compare two strings (case-sensitive, Hello and hELLo output are different):

<?php
echo strncmp("Hello","Hello",6);
echo "<br>";
echo strncmp("Hello","hELLo",6);
?>

Example This example uses the strncmp function to compare the specified length String.

int main()
{
  char str1[]="Hello",str2[]="Help",str3[]="Hello";
  int a,b,c;
  a = strncmp(str1,str2,3);    //比较字符串str1,str2前3个字符
  b = strncmp(str2,str3,4);     //比较字符串str2,str3前4个字符
  c = strncmp(str1,str2,4);     //比较字符串str1,str2前4个字符
  cout<<a<<"\t"<<b<<"\t"<<c<<"\n";
}

Run result:

0 1 -1

The above is the detailed content of PHP function strncmp() for string comparison of the first n characters (case sensitive). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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