View previous topic :: View next topic |
Author |
Message |
raman00084@gmail.com
Joined: 28 Jul 2014 Posts: 38
|
comparing 2 strings |
Posted: Wed Apr 07, 2021 5:05 am |
|
|
How can i compare 2 string arrays using ccs string compare function ?
I am using pic18f4620.
Example:
Code: |
char name_buf_1[]={"kalyn"};
char name_buf_2[]={"kalyn"};
|
How can i compare name_buf_1 and name_buf_2 ? |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19506
|
|
Posted: Wed Apr 07, 2021 6:18 am |
|
|
Er. Use the string compare function!....
if (strcmp(name_buf_1, name_buf_2)==0)
The strings are then the same. Key thing to understand is that strcmp, does
not return a simple 'true/false'. It returns '0' of the strings match, but if they
differ, it returns a signed value reflecting which is 'lower' (in ASCII terms)
than the other, so -1 if the second string is lower than the first and 1 if
the first is lower than the second. |
|
|
temtronic
Joined: 01 Jul 2010 Posts: 9225 Location: Greensville,Ontario
|
|
Posted: Wed Apr 07, 2021 6:19 am |
|
|
Quick Comment..
I've never used it, saw this in the manual...
if(strcmp(string, password))
printf("OK");
so something like...
if(strcmp(name_buf_1,name_buf_2)) print ("they are the same");
...might work for you ??
Probably have to include a 'library' first though...
Jay |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19506
|
|
Posted: Wed Apr 07, 2021 6:36 am |
|
|
It is in string.h
However what you post is the wrong way round. As I explained, strcmp, does
not return TRUE/FALSE. It actually returns 'FALSE' if the strings match!.
It returns:
-1 s1>s2
0 s1==s2
1 s1<s2
It is using 'TRUE', and then finding it never works that is why this confuses!... |
|
|
temtronic
Joined: 01 Jul 2010 Posts: 9225 Location: Greensville,Ontario
|
|
Posted: Wed Apr 07, 2021 7:02 am |
|
|
dang, you're a faster typer than me, Mr.T !!
I love the logic....0 means the same... reminds me of my QB45 dayze.... |
|
|
newguy
Joined: 24 Jun 2004 Posts: 1907
|
|
Posted: Wed Apr 07, 2021 5:08 pm |
|
|
The return value makes total sense if you consider how the comparison is done.
In a for() loop, subtract each element of s1 from s2. If the result is 0, continue. If it's negative, return -1. If it's positive, return 1. If you hit the end and neither of the above applies, return 0. Simple. And no issues with translating the values to correspond with a human's affinity for 'positive logic'. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19506
|
|
Posted: Wed Apr 07, 2021 11:34 pm |
|
|
Absolutely, and also returning the comparison like this makes it suitable
for use with qsort.
However the issue is that people "don't read the manual", and expect it
to return 'TRUE' when the strings match, and then get puzzled when it
doesn't work.... |
|
|
|