C-language string comparisons

Source: Internet
Author: User
Tags strcmp

#include <string.h>
Char s1[10],s2[10]; ... if (strcmp (S1,S2) ==0) printf ("Two strings equal \ n");
There is a comparison function in the String.h header file that can be used to compare equality

2: This is the normal method does not call function strcmp ();
#include &lt;stdio.h&gt;

int comparision (char A[],char b[])
{
int t,i=0;
while (a[i]!= ' | | b[i]!= ' + ')
{
if (A[i]==b[i]) t=0;
else if (a[i]&gt;b[i]) t=1;
else T=-1;
if (t!=0) break;
i++;
}
return t;
}

Main (void)
{
Char a[40],b[40];
int k=0;
Gets (a);
Gets (b);
K=comparision (A, b);
if (k==1) printf ("a[40]&gt;b[40]");
else if (k==-1) printf ("a[40]&lt;b[40]");
else printf ("a[40]=b[40]");
}

Why are two strings not directly comparable in the "doubts" C language?

As we all know, in the C language two strings are not directly compared, we generally use the <string.h> string comparison function strcmp () to do two string comparison. So why not allow two strings to be compared directly? The following explanations can be made:
Have the following code: Char s1[] = "ABC"; Char s2[] = "ABC";
If you are comparing directly: if (S1 = = s2) {printf ("S1 equals S2"),} else {printf ("S1 Not equal to S2");}
What do you think the output will be?
The output is always: S1 is not equal to S2. (Whether you change to char s1[] = "abc", char s2[] = "def", or char s1[] = "def"; char s2[] = "abc"; output is the same).
Why is it? As a result of this comparison, we are actually comparing S1 and S2 as pointers, rather than comparing the contents of two arrays. Because S1 and S2 in memory location certainly different, so S1 = = S2 value is certainly 0, so the result of the above is taken for granted.

This should be traceable to the access mechanism of arrays in C (strings can also be considered arrays)

From

C language string comparison (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.