实现strcmp、strncmp、strchr、strpbrk
cpp
int my_strcmp(char *s1, char *s2)
{
if (s1 == NULL && s2 == NULL)
{
return 0;
}
if (s1 != NULL && s2 == NULL)
{
return 1;
}
if (s1 == NULL && s2 != NULL)
{
return -1;
}
while (*s1 != '\0' && *s2 != '\0')
{
if (*s1 > *s2)
{
return 1;
}
else if (*s1 < *s2)
{
return -1;
}
s1++;
s2++;
}
if (*s1 == '\0' && *s2 == '\0')
{
return 0;
}
if (*s1 != '\0' && *s2 == '\0')
{
return 1;
}
if (*s1 == '\0' && *s2 != '\0')
{
return -1;
}
}
int my_strncmp(char *s1, char *s2, size_t n)
{
if (s1 == NULL || s2 == NULL)
{
return -1;
}
for (int i = 0; (i < n && (*s1 != '\0' && *s2 != '\0')); i++)
{
if (s1[i] != s2[i])
{
return -1;
}
}
return 0;
}
char *my_strchr(char *s, int c)
{
while (*s != '\0')
{
if (*s == c)
{
return s;
}
else
{
s++;
}
}
}
char *my_strpbrk(char *s, char *accept)
{
char *temp = accept;
char *result = NULL;
while (*accept != '\0')
{
temp = strchr(s, *accept); // 查找accept第一次在字符s中出现的位置
if (temp != NULL) // 如果找到
{
result = temp; // 将第一次找到的位置赋值给result
while (*accept != '\0') // 再次遍历
{
temp = strchr(s, *accept); // 再次查找
if (temp != NULL && temp < result) // 如果找到且比第一次找到的位置更靠左,则取
{
result = temp; // 赋值给result
}
accept++; // 指针后移
}
return result; // 返回结果
}
}
}