字符函数
- 11.1求字符串长度
- strlen
- strlen模拟
- 11.2长度不受限制的字符串函数
- strcpy
11.1求字符串长度
strlen
Get the length of a string.
size_t strlen( const char *string );
typedef unsigned int size_t;
strlen 返回值为 unsigned int
strlen返回字符串中 \0
前面出现的字符个数
参数指向的字符串必须要以\0
结束
int main() {char arr[] = "hello ruarua";printf("%u\n", strlen(arr));return 0;
}
strlen模拟
//方案1.计数器
size_t my_strlen(const char* str){int count = 0;while (*str != '\0') {count++;str++;}return count;
}
//方案2.指针-指针
size_t my_strlen(const char* str) {char* end = str;while (*end != '\0')end++;return end - str;
}
//方案3.递归
size_t my_strlen(const char* str) {if (*str == 0)return 0;elsereturn 1 + my_strlen(str + 1);
}int main() {int sz = my_strlen("ruarua");printf("%u\n", sz);//%u unsigned intreturn 0;
}
11.2长度不受限制的字符串函数
strcpy
Copy a string.
char *strcpy( char *strDestination, const char *strSource );
源字符串必须以\0
结束,\0
会拷贝到目标空间。
目标空间必须足够大,以确保能存放源字符串。
目标空间必须可修改。
int main() {char arr1[20] = { 0 };char arr2[] = "hello ruarua";//char arr2[] = {'r','u','a'};//没有'\0' errstrcpy(arr1, arr2);printf("%s\n", arr1);return 0;
}
模拟strcpy
#include <assert.h>
char* my_strcpy(char* dest, const char* src) {assert(dest != NULL);assert(src != NULL);char* ret = dest;while (*src != '\0') {*dest = *src;dest++;src++;}*dest = *src;//copy '\0'return ret;
}
//简化-->
char* my_strcpy(char* dest, const char* src) {assert(dest != NULL);assert(src != NULL);char* ret = dest;while (*dest++ = *src++) {;}return ret;
}int main() {char arr1[20] = { 0 };char arr2[] = "hello ruarua";my_strcpy(arr1, arr2);printf("%s\n", arr1);return 0;
}