用c语言实现编写程序实现字符串的基本操作,包括求串长,赋值,比较,串连接,求子串
时间: 2024-05-07 08:15:28 浏览: 71
以下是用C语言实现字符串的基本操作的代码:
```c
#include <stdio.h>
#include <string.h>
// 求字符串长度
int strlen(char *s) {
int len = 0;
while (*s) {
len++;
s++;
}
return len;
}
// 字符串赋值
void strcpy(char *dest, char *src) {
while (*src) {
*dest = *src;
dest++;
src++;
}
*dest = '\0';
}
// 字符串比较
int strcmp(char *s1, char *s2) {
while (*s1 && *s2 && (*s1 == *s2)) {
s1++;
s2++;
}
return (*s1 - *s2);
}
// 字符串连接
void strcat(char *dest, char *src) {
while (*dest) {
dest++;
}
while (*src) {
*dest = *src;
dest++;
src++;
}
*dest = '\0';
}
// 求子串
char* substr(char *s, int start, int len) {
char *sub = (char*)malloc((len + 1) * sizeof(char));
int i;
for (i = 0; i < len; i++) {
sub[i] = s[start + i];
}
sub[len] = '\0';
return sub;
}
int main() {
char s1[100] = "Hello, world!";
char s2[100] = "C programming";
char *sub;
// 求字符串长度
printf("Length of s1: %d\n", strlen(s1));
printf("Length of s2: %d\n", strlen(s2));
// 字符串赋值
strcpy(s1, s2);
printf("After copying s2 to s1: %s\n", s1);
// 字符串比较
if (strcmp(s1, s2) == 0) {
printf("s1 and s2 are equal\n");
} else {
printf("s1 and s2 are not equal\n");
}
// 字符串连接
strcat(s1, " and ");
strcat(s1, "C++ programming");
printf("After concatenating: %s\n", s1);
// 求子串
sub = substr(s1, 5, 10);
printf("Substring of s1: %s\n", sub);
free(sub);
return 0;
}
```
输出结果:
```
Length of s1: 13
Length of s2: 14
After copying s2 to s1: C programming
s1 and s2 are not equal
After concatenating: C programming and C++ programming
Substring of s1: o programming
```
阅读全文