Home > Backend Development > PHP Tutorial > 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)

黄舟
Release: 2023-03-17 06:44:01
Original
2239 people have browsed it

Example

Compare two strings (case sensitive):

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

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)
Copy after login
ParametersDescription
string1 Required. Specifies the first string to compare.
string2Required. Specifies the second string to be compared.
lengthRequired. 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

  • ##<0 - if string1 is less than string2

  • >0 - 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);
?>
Copy after login

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";
}
Copy after login

Run result:

0 1 -1
Copy after login

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!

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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template