c语言中的字符串
字符串在c语言中的含义
- c语言中没有为字符串设置单独的数据类型,而是通过字符数组实现的。定义字符串的语法:char str[n] = “”,其中n可以不用填写让编译器自己取计算字符数组有几个字符数。
// 语法格式
char str[10] = "hello";
char str1[] = "c language";
char *str2 = "Java";
字符串API
- strcpy(dest,src) 字符串赋值或复制,特点是不安全,内部没有做边界判断。
- strncpy(dest,src,n) 指定复制的字符数量来进行字符串赋值或复制,特点是安全,不会溢出字符串边界。
- strcat(dest,src) 字符串拼接,将src全部拼接到dest。拼接的过程中可能导致最终字符数超过dest的最大容量,出现溢出情况,这个时候多余的部分会复制到dest的相邻其他内存区,这样是不安全的。
- strncat(dest,src,n) 指定拼接src中n个字符到dest尾部。其中n必须保证最后拼接的字符数量不超过dest的最大容量。
- strcmp(s1,s2) 字符串比较,特点比较的是整个字符串。
- strncmp(s1,s2,n) n表示比较的字符数量,也可以理解为字符比较的结束位置。
// strcpy 简单实现
char *strcpy1(char *dest, const char *src)
{
char *p = dest;
// dest++这个操作存在溢出风险
while (*dest++ = *src++);
return p;
}
// strncpy 简单实现
char *strncpy1(char *dest, const char *src, size_t n)
{
size_t count = 0;
char *p = dest;
while (count < n)
{
*dest++ = *src++;
count++;
}
// 最后一个字符填充' '
*dest++ = ' ';
}
// strcat简单实现
char *strcat1(char *s1, const char *s2)
{
int n_s1 = strlen(s1);
s1 += n_s1;
// s1++ 这个操作存在溢出的风险
while (*s1++ = *s2++);
}
// strncat简单实现
char *strncat1(char *s1, const char *s2, size_t n)
{
int n_s1 = strlen(s1);
int count = 0;
s1 += n_s1;
while (count < n)
{
*s1++ = *s2++;
count++;
}
}
// strcmp简单实现
int strcmp1(const char *s1, const char *s2)
{
int len1 = strlen(s1);
int len2 = strlen(s2);
int count = 0;
while (*s1 && *s2)
{
count++;
if (*s1++ != *s2++)
{
s1--;
s2--;
break;
}
}
if ((count == len1 || count == len2) && *s1 == *s2)
{
return 0;
}
else
{
if (*s1 > *s2)
{
return 1;
}
else
{
return -1;
}
}
}
// strncmp简单实现
int strncmp1(const char *s1, const char *s2, size_t n)
{
int len1 = strlen(s1);
int len2 = strlen(s2);
int count = 0;
while (*s1 && *s2 && count < n)
{
count++;
if (*s1 != *s2)
{
if (*s1 > *s2)
{
return 1;
}
else
{
return -1;
}
}
s1++;
s2++;
}
s1--;
s2--;
// 其中一个字符串中最后一个字符的情况
if (count == len1 || count == len2)
{
if (*s1 == *s2)
{
if (count == n)
{
return 0;
}
else if (count < len1)
{
return 1;
}
else if (count < len2)
{
return -1;
}
return 0;
}
else if (*s1 > *s2)
{
return 1;
}
else
{
return -1;
}
}
else
{
s1--;
s2--;
if (*s1 == *s2)
{
return 0;
}
else if (*s1 > *s2)
{
return 1;
}
else
{
return -1;
}
}
}
- 现在最后:欢迎大家来指正,这写代码都是学习API的时候写的,目前还没有发现任何问题,但是决定程序的编写不可能面面俱到的,可能还存在遗漏的情况,所以恳请大家来找出问题。