C语言中定义字符串的一个问题
C语言中一般定义字符串有两种形式,一种是char str[]
这种方式只开辟了一个数组空间。另一种char *str
这种方式开辟了两个空间,一个指针空间和一个常量区的空间,所以这种方式定义的字符串是一个常量,多在不对其做修改的情况下使用。用相同常量初始化不同数组时会开辟不用空间。例如str1[]={"HELLO"}; str2[]={"HELLO"}; str1 != str2
.
strlen函数
size_t strlen(const char *str);
strlen函数可以求字符串的字符个数。函数返回字符串的个数,但是不包含终止符,有一个字符指针的参数,如果参数传入NULL,返回error。
库函数strlen的模拟实现
#include<stdio.h>
#include<assert.h>
int my_strlen(const char *str) {
int count = 0;
assert(str != NULL);
while (*str != '\0') {
count++;
str++;
}
return count;
}
strcpy函数
char *strcpy(chra* destination,const char *source);
字符串拷贝函数,它把一个字符串内容复制到另一个地址空间中,包含\0,函数包含两个参数,都是字符指针类型,返回目标字符串的地址空间。拷贝过程中目标空间必须足够大。目标空间里的值必须是可以修改的。
strcpy函数的模拟实现
#include<stdio.h>
#include<assert.h>
#include<string.h>
char* my_strcpy(char *Destnation,const char *Source) {
assert(Destnation != NULL && Source != NULL);
//使用临时变量保护参数
char *ptmpdest = Destnation;
const char* ptmpsour = Source;
while (*ptmpsour !='\0') {
*ptmpdest++ = *ptmpsour++;
}
*ptmpdest = '\0';
//返回目标空间的地址
return Destnation;
}
strcat函数
char * strcat(char *destination, const char *source)
strcat字符串链接函数,将源字符串链接到目标字符串末尾。返回目标字符串的地址。
库函数strcat的模拟实现
#include<stdio.h>
#include<assert.h>
char* my_strcat(char* Destnation, const char* Source) {
assert(Destnation != NULL && Source != NULL);
char* ptmp = Destnation;
while (*ptmp != '\0') {
ptmp++;
}
while (*Source !=