C语言本身是没有字符串类型的,但是C语言中对字符和字符串的处理却很频繁。
(一)字符函数
1.1 strlen - 求字符串的长度,以'\0'作为结束的标志,返回的是‘\0’前面出现的字符个数,返回值为size_t, 是无符号的;
size_t strlen ( const char * str );
头文件 <string.h>;
模拟实现strlen:
#include<stdio.h>
int my_strlen(char* ps)
{
int count = 0;
while(*ps)
{
count++;
ps++;
}
return count;
}
int main()
{
char arr[] = "abcdefg";
int ret = my_strlen(arr);
printf("%d", ret);
return 0;
}
1.2 strcpy - 字符换拷贝;Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).
char * strcpy ( char * destination, const char * source );//这里的返回值类型设置为char*是可以将返回值作为参数实现链式访问;
模拟实现strcpy :
#include<stdio.h>
#include<assert.h>
char* my_strcpy(char* dest, const char* src)
{
char* ret = dest;
assert(dest && src);
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[20] = "**************";
char arr2[] = "abcdefg";
my_strcpy(arr1, arr2);//将arr2拷贝到arr1里面
printf("%s", arr1);
return 0;
总结:源字符串arr2必须包含'\0';并且'\0'会一起拷贝到arr1中;arr1的空间必须足够大且可变;
1.3 strcat - 字符串连接;
char * strcat ( char * destination, const char * source );
Concatenate strings
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.
destination and source shall not overlap.
模拟实现strcat :
char* my_strcat(char* dest, const char* src)
{
assert(dest && src);
char* ret = dest;
while (*dest)
{
dest++;
}
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[30] = "today is my ";
char arr2[] = "lucky day";
printf("%s", my_strcat(arr1, arr2));
return 0;
}
总结:源字符串必须以‘\0’结束,并且目标空间必须足够大,可修改;
注意:字符串自身不能给自身追加,就是比如 my_strcat(arr1, arr1),这样'\0'会被覆盖,就会找不到停下来的标志;
1.4 strcmp - 字符串比较,
int strcmp ( const char * str1, const char * str2 )
Compares the C string str1 to the C string str2.
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
Returns an integral value indicating the relationship between the strings:
Return Value
return value | indicates |
---|---|
<0 | the first character that does not match has a lower value in ptr1 than in ptr2 |
0 | the contents of both strings are equal |
>0 | the first character that does not match has a greater value in ptr1 than in ptr2 |
模拟实现strcmp :
int my_strcmp(const char* str1, const char* str2)
{
assert(str1 && str2);
while (*str1 == *str2)
{
if (*str1 == '\0')
return 0;
str1++;
str2++;
}
return(*str1 - *str2);//字符在内存中是以ASCII码值存储的;
}
int main()
{
char arr1[] = "abcdefg";
char arr2[] = "abcde";
int ret = my_strcmp(arr1, arr2);
if (ret == 0)
printf("arr1和arr2相等\n");
else
printf("arr1和arr2不相等\n");
return 0;
}
总结:以上的字符串长度不受限制,只关注\0;
可以和strncpy,strncat,strncmp进行比较学习;