用c语言写串的增、删、改、查简单代码
时间: 2023-07-10 12:03:27 浏览: 87
以下是一个简单的串操作的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 50
typedef struct {
char str[MAXLEN+1]; // 存储串的数组
int len; // 串的长度
} String;
// 初始化串
void InitString(String *s, char *str) {
int len = strlen(str);
if (len > MAXLEN) {
printf("Error: string is too long\n");
exit(1);
}
strcpy(s->str, str);
s->len = len;
}
// 打印串
void PrintString(String *s) {
printf("%s\n", s->str);
}
// 在串中插入子串
void InsertString(String *s, int pos, char *sub) {
int sublen = strlen(sub);
if (s->len + sublen > MAXLEN) {
printf("Error: string is too long\n");
exit(1);
}
if (pos < 1 || pos > s->len+1) {
printf("Error: invalid position\n");
exit(1);
}
// 先把pos及之后的字符后移sublen个位置
for (int i = s->len; i >= pos; i--) {
s->str[i+sublen] = s->str[i];
}
// 再将子串插入到pos位置
for (int i = 0; i < sublen; i++) {
s->str[pos+i-1] = sub[i];
}
s->len += sublen;
}
// 删除串中的子串
void DeleteString(String *s, int pos, int len) {
if (pos < 1 || pos > s->len) {
printf("Error: invalid position\n");
exit(1);
}
if (len < 0 || pos+len-1 > s->len) {
printf("Error: invalid length\n");
exit(1);
}
// 先把pos+len及之后的字符前移len个位置
for (int i = pos+len; i <= s->len; i++) {
s->str[i-len] = s->str[i];
}
s->len -= len;
}
// 替换串中的子串
void ReplaceString(String *s, int pos, int len, char *sub) {
DeleteString(s, pos, len);
InsertString(s, pos, sub);
}
// 查找子串
int FindString(String *s, char *sub) {
char *p = strstr(s->str, sub);
if (p == NULL) {
return -1;
} else {
return p - s->str + 1;
}
}
int main() {
String s;
InitString(&s, "Hello, world!");
PrintString(&s);
InsertString(&s, 8, "C language ");
PrintString(&s);
ReplaceString(&s, 8, 9, "programming");
PrintString(&s);
DeleteString(&s, 8, 11);
PrintString(&s);
int pos = FindString(&s, "world");
if (pos == -1) {
printf("Not found\n");
} else {
printf("Found at position %d\n", pos);
}
return 0;
}
```
参考文献:[《数据结构与算法分析》(第3版)](https://book.douban.com/subject/30370902/)
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)