编写6个字符串处理函数C语言
时间: 2023-11-27 19:51:04 浏览: 157
1. strlen(): 计算字符串长度
```c
int strlen(const char *str) {
int len = 0;
while (str[len] != '\0') {
len++;
}
return len;
}
```
2. strcpy(): 复制字符串
```c
char* strcpy(char *dest, const char *src) {
char *p = dest;
while (*src != '\0') {
*p++ = *src++;
}
*p = '\0';
return dest;
}
```
3. strcat(): 连接两个字符串
```c
char* strcat(char *dest, const char *src) {
char *p = dest + strlen(dest);
while (*src != '\0') {
*p++ = *src++;
}
*p = '\0';
return dest;
}
```
4. strcmp(): 比较两个字符串
```c
int strcmp(const char *str1, const char *str2) {
while (*str1 == *str2) {
if (*str1 == '\0') {
return 0;
}
str1++;
str2++;
}
return (*str1 > *str2) ? 1 : -1;
}
```
5. strstr(): 在一个字符串中查找另一个字符串
```c
char* strstr(const char *str1, const char *str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);
if (len2 > len1) {
return NULL;
}
for (int i = 0; i <= len1 - len2; i++) {
if (strncmp(str1 + i, str2, len2) == 0) {
return (char*)(str1 + i);
}
}
return NULL;
}
```
6. strtok(): 分割字符串
```c
char* strtok(char *str, const char *delim) {
static char *s = NULL;
if (str != NULL) {
s = str;
}
if (s == NULL) {
return NULL;
}
char *p = s;
while (*p != '\0' && strchr(delim, *p) != NULL) {
p++;
}
if (*p == '\0') {
s = NULL;
return NULL;
}
char *q = p;
while (*q != '\0' && strchr(delim, *q) == NULL) {
q++;
}
if (*q == '\0') {
s = NULL;
} else {
*q = '\0';
s = q + 1;
}
return p;
}
```
阅读全文