字符串相关函数
一、字符串的复制
1、指针形式
void Mystrcpy(char *des, const char *src)
{
//1,
/*while(*src!='\0')
{
*des = *src;
des++;
src++;
}*/
//2,
/*while (*src != '\0')
{
*des++ = *src++;//优先级: ++ 高于 * 高于 =
}*/
//3,
//while (*des++ = *src++)
*des = '\0';
}
int main()
{
char str1[] = "abcdefg";//不能写成char *str1 = "abcdefg";
//因为指针不是自己的空间,是指向字符常量的,不能被修改
char *str2 = "hello";
Mystrcpy(str1, str2);
//4,strcpy(str1, str2);
printf("%s\n", str1);
//5,
//printf("%s\n", strcpy(str1, str2));//支持链式表达
return 0;
}
2、数组形式
void Mystrcpy(char *des, char *src)
{
int i;
for (i = 0; src[i] != '\0'; i++)
{
des[i] = src[i];
}
des[i] = '\0';//加上\0后表示无论arr有多长,都可以结束复制
}
int main()
{
char arr[] = "hellojfksd";
char brr[] = "world";
Mystrcpy(arr, brr);
printf("%s\n", arr);
return 0;
}
二、字符串的连接
char *Mystrcat(char *str1,char*str2)
{
char *begin = str1;
while( *str1!='\0' )
{
str1++;
}
while (*str2 != '\0')
{
*str1++= *str2++;
}
*str1 = '\0';//字符串遇见‘\0’才算结束
return begin;
}
int main()
{
char str1[20] = "abcde";
char *str2 = "hello";
Mystrcat(str1, str2);
printf("%s\n", str1);
return 0;
}
三、字符串的比较
字符串比较的是ASCII的值,并不是字符串的长短
int Mystrcmp(const char *str1, const char*str2)
{
while (*str1 == *str2)
{
if (*str1 == '\0')
{
return 0;
}
str1++;
str2++;
}
if (*str1 > *str2)
{
return 1;
}
else
{
return -1;
}
}
int main()
{
char *str1 = "abcdef";
char *str2 = "abcde";
printf("%d\n", Mystrcmp(str1, str2));
return 0;
}
四、字符串与数字之间的转换
1、将数字转为字符串形式//1234->“1234”
char *Myitoa(char *str, int num)
{
int i = 0;
while (num != 0)
{
str[i] = num % 10 + 48;//48是‘\0’的ASCII的值
i++;
num /= 10;
}
str[i] = '\0';
//此时str中是数组的逆置
i--;//--后才是数组的下标
char tmp = 0;
for (int j = 0; j < i; i--, j++)
{
tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
return str;
}
int main()
{
char src[100];
int a = 1234;
Myitoa(src, a);
printf("%s\n", src);
return 0;
}
2、将数字字符串转为数字形式 //“1234”->1234,“a123”->0,“12a34”->12
int Myatoi(const char *str)
{
int flg = 1;
int tmp = 0;
assert( str != NULL);//判空
while (*str == ' ')
{
str++;
}
if (*str == '-')
{
flg = -1;
str++;
}
else if (*str == '+')
{
flg = 1;
str++;
}
while (isdigit(*str))//isdigit函数,主要用于检查其参数是否为十进制数字字符
//C语言中需要加上头文件#include <ctype.h>,C++加上#include<cctype>
{
tmp = tmp * 10 + *str - '0';
str++;
}
return flg *tmp;
}
int main()
{
char str1[100] = "12a 34";
char str2[100] = "a1223";
char str3[100] = "-123";
printf("%d\n", Myatoi(str1));
printf("%d\n", Myatoi(str2));
printf("%d\n", Myatoi(str3));
return 0;
}