醒啦C++用任意一种存储方式实现串的新建、插入与删除操作
时间: 2024-05-01 22:17:09 浏览: 28
以下是用 C 语言使用数组实现串的新建、插入和删除操作的示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 1000 // 串的最大长度
// 新建一个空串
void createString(char str[]) {
str[0] = '\0';
}
// 插入字符串 s 到串 str 的指定位置 pos
void insertString(char str[], char s[], int pos) {
int len1 = strlen(str);
int len2 = strlen(s);
if (len1 + len2 > MAX_LENGTH) {
printf("插入后的字符串长度超过了最大长度 %d\n", MAX_LENGTH);
return;
}
if (pos < 0 || pos > len1) {
printf("插入位置不合法\n");
return;
}
// 先将插入位置后面的字符后移
for (int i = len1; i >= pos; i--) {
str[i + len2] = str[i];
}
// 将 s 插入到指定位置
for (int i = 0; i < len2; i++) {
str[pos + i] = s[i];
}
str[len1 + len2] = '\0';
}
// 从串 str 中删除指定位置 pos 开始的 len 个字符
void deleteString(char str[], int pos, int len) {
int len1 = strlen(str);
if (pos < 0 || pos >= len1) {
printf("删除位置不合法\n");
return;
}
if (pos + len > len1) {
printf("要删除的字符数超过了字符串长度\n");
return;
}
for (int i = pos + len; i <= len1; i++) {
str[i - len] = str[i];
}
str[len1 - len] = '\0';
}
int main() {
char str[MAX_LENGTH];
// 新建一个空串
createString(str);
printf("新建一个空串:%s\n", str);
// 插入字符串
insertString(str, "hello", 0);
printf("插入字符串 hello:%s\n", str);
// 插入字符串到指定位置
insertString(str, "world", 5);
printf("插入字符串 world 到位置 5:%s\n", str);
// 删除指定位置的字符
deleteString(str, 5, 5);
printf("删除位置 5 开始的 5 个字符:%s\n", str);
return 0;
}
```
输出结果:
```
新建一个空串:
插入字符串 hello:hello
插入字符串 world 到位置 5:helloworld
删除位置 5 开始的 5 个字符:hello
```
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)