用c语言实现字符串的初始操作,包括求串长,赋值,比较,串连接,求子串,替换和定位算法
时间: 2024-05-14 19:15:18 浏览: 55
1. 求串长:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
int len = strlen(str);
printf("The length of the string is %d\n", len);
return 0;
}
```
2. 赋值:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "hello";
char str2[20];
strcpy(str2, str1);
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
return 0;
}
```
3. 比较:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "hello";
char str2[20] = "world";
int result = strcmp(str1, str2);
if (result < 0) {
printf("%s < %s\n", str1, str2);
} else if (result == 0) {
printf("%s = %s\n", str1, str2);
} else {
printf("%s > %s\n", str1, str2);
}
return 0;
}
```
4. 串连接:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "hello";
char str2[20] = "world";
strcat(str1, str2);
printf("%s\n", str1);
return 0;
}
```
5. 求子串:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "hello world";
char str2[10];
strncpy(str2, str1+6, 5);
printf("%s\n", str2);
return 0;
}
```
6. 替换:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
char *result = strstr(str, "world");
if (result) {
strncpy(result, "c", 1);
}
printf("%s\n", str);
return 0;
}
```
7. 定位算法:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
char *result = strchr(str, 'o');
if (result) {
printf("The index of the first 'o' is %ld\n", result - str);
}
return 0;
}
```
阅读全文