Please explain this method for comparing strings
Suppose, for example, that some k
which is an arbitrary number=2 k=2
, then there is code in C:
int wordcomp(char *p, char *q) {
int n = k;
for ( ; *p == *q ; p++, q++) {
if ( *p==0 &a开发者_如何学Cmp;& --n == 0 )
return 0;
}
return *p - *q;
}
Please explain to me what this code does? Also, what does *p-*q
mean? Also, how is it implemented in Java?
please explain me what does this code do?
It compares two words
also what means
*p-*q
?
It means, Tell me the value of char the pointer p is pointing to, and rest it to the char the pointer q is pointing to.
and also how implement it in java?
The *p-*q
part? Here is it.
// char c
// char k
c - k;
If you mean the whole function, this could help you to get started:
int wordcomp( String sp, String sq) {
int n = k; // I have no idea what is this for
int pi = 0, qi = 0;
for ( ; sp.charAt(pi) == sq.charAt(qi) ; pi++, qi++) {
if ( sp.length()==pi && --n == 0 )
return 0;
}
return sp.charAt(pi) - sq.charAt(qi);
You need to validate limits tough.
Looks to be close to strcmp. It takes two string pointers, loops over them until it finds a character that is different, and then returns a positive value if p is alphabetically after q, a negative value if p is alphabetically before q, or 0 if they are the same. As stated by others, k looks to define the number of consecutive null-terminated strings to compare before it just returns 0.
*p-*q
means subtract the value pointed to by pointer q from the value pointed to by pointer p.
this being C, subtracting 2 char values means subtracting their ASCII codes.
This function loops through two character arrays, comparing them for equality.
If they are unequal, it returns *p - *q, which is the difference between the values in the first unequal position. If, after the kth zero in the first string, there is still no inequality, then it returns 0.
So it returns the difference between the values in the first unequal position, or 0 if the first string has k zeros and is equal until that point to the second string.
Returns the difference between the first two dissimilar char
s in two character arrays (*p
and *q
) of maximum length k
, i.e.
batter
batsman
Returns 't'-'s'
If both strings are same for length k
and we reach the null character of p
, we return 0
. I think it should be ||
not &&
since these are termination conditions.
It compares to char arrays (words) to the element set in k. Lets say if you have k=4 it means it will compare first 4 chars. Also I believe instead of
if ( *p==0 && --n==0)
you need
if ( *p==0 || --n==0)
And also please consider using p - q
.
And the function name must be wordcomp
instead of wrodcomp
.
So to summarize it is something like strncmp
from string.h
.
精彩评论