统计字符串中单词的个数
int NumWord(char *str)
{
assert(str != NULL);
int count = 0;
while (*str != 0)
{
if (isalpha(*str) && !isalpha(*(str + 1)))
{
count++;
}
str++;
}
}
将一个字符串的前n位复制到新的字符串中
char *My_strncpy(char *dest, char *src, int n)
{
assert(dest != NULL && src != NULL);
assert(n > 0 && n < strlen(src));
char *p = dest;
for (int i = 0; *src != '\0'&&i < n; i++)
{
dest[i] = src[i];
}
return p;
}
将字符转化为数字
int My_atoi(char *str)将字符串转化为数字
{
int num = 0;
while (*str = ' ')
{
str++;
}
while (*str == '-')
{
printf("-");
str++;
}
while (isdigit(*str))
{
num = num * 10 + (*str - '0');
str++;
}
return num;
}
将数字转化为字符
char *My_itoa(char *str, int num)
{
int i = 0;
while (num != 0)
{
str[i] = num % 10 + '0';
num = num / 10;
i++;
}
str[i] = '\0';
i--;
for (int j = 0; j < i; j++, i--)
{
char ch = str[j];
str[j] = str[i];
str[i] = ch;
}
return str;
}
比较两个字符串是否相等
int My_strcmp(const char *str1, const char *str2)
{
int tmp = 0;
while ((tmp = *str1 - *str2) == 0 && *str2 != '\0')
{
str1++;
str2++;
}
return tmp;
}
比较两个字符串的前n个字符是否相等
int My_strcmp(const char *str1, const char *str2, int n)
{
int tmp = 0;
int i = 1;
while ((tmp = *str1 - *str2) == 0 && *str2 != '\0'&&i < n)
{
str1++;
str2++;
i++;
}
return tmp;
}