Function takes in two strings, want to compare nth character
I have a f开发者_JAVA百科unction that takes in two strings, and I want to, let's say compare the 2nd letter of each string to the other. How do I fix this statement:
if (strncmp(str1 + 1, str2 + 1) != 0) {
...
I get an error stating that passing the argument makes a pointer from an integer without a cast.
if (str1[1] == str2[1]) {
/* Do something */
}
If you want to allow the possibility that any of the strings can be smaller than the position you want to compare:
/* Return 1 if s1[n] > s2[n], 0 if s1[n] == s2[n], -1 if s1[n] < s2[n].
Return -2 if any of the strings is smaller than n bytes long. */
int compare_nth(const char *s1, const char *s2, size_t n)
{
size_t i;
for (i=0; i < n; ++i)
if (s1[i] == 0 || s2[i] == 0)
return -2;
if (s1[n] < s2[n])
return -1;
else if (s1[n] > s2[n])
return 1;
else
return 0;
}
Then, to do something when the n
th characters are equal, you can do:
if (compare_nth(s1, s2, n) == 0) {
/* do whatever you want to do here */
}
If you know for sure that there are at least n
characters in each of the strings, you can just do what others said:
if (s1[n] == s2[n]) {
/* do whatever you want to do here */
}
(Note: since indexing in C is from 0, n
is used in the same sense here. So, to test the second characters, n
would be 1
.)
精彩评论