用c语言编写一个程序,使它具有:对串进行初始化,创建,求子串,删除插入子串集一体的操作,并且进行什么操作是由我们进行选择的
时间: 2024-10-22 21:18:30 浏览: 36
在C语言中,你可以创建一个结构体来表示字符串及其相关的操作,并设计一个主函数来接收用户的输入选择相应操作。下面是一个简单的示例程序:
```c
#include <stdio.h>
#include <string.h>
// 定义字符串结构体
typedef struct {
char* str;
int len;
} String;
// 初始化字符串
String init_string(char* input) {
String s = {input, strlen(input)};
return s;
}
// 创建新字符串
String create_string(String base, char* new_str) {
char* combined = (char*) malloc(strlen(base.str) + strlen(new_str) + 1);
strcpy(combined, base.str);
strcat(combined, new_str);
String result = {combined, strlen(combined)};
return result;
}
// 求子串
void get_substring(String s, int start, int end) {
printf("Substring from %d to %d is: %s\n", start, end, s.str + start);
}
// 删除子串
void delete_substring(String* s, int start, int length) {
memmove(s->str + start, s->str + start + length, s->len - start - length);
s->len -= length;
}
// 插入子串
void insert_substring(String* s, int index, char* insert) {
char* temp = (char*) realloc(s->str, s->len + strlen(insert) + 1);
if (temp == NULL) {
printf("Memory allocation failed.\n");
return;
}
memmove(temp + index, temp + index + strlen(insert), s->len - index);
strcpy(temp + index, insert);
s->str = temp;
s->len += strlen(insert);
}
int main() {
String original;
printf("Enter a string for initialization: ");
fgets(original.str, sizeof(original.str), stdin);
original.str[strcspn(original.str, "\n")] = '\0'; // Remove newline
while (1) {
printf("\nChoose an operation:\n1. Initialize\n2. Create\n3. Get substring\n4. Delete substring\n5. Insert substring\n6. Exit\n");
int choice;
scanf("%d", &choice);
switch (choice) {
case 1:
break; // No action needed as the string is already initialized
case 2:
char new_input[100];
printf("Enter a string to append: ");
fgets(new_input, sizeof(new_input), stdin);
new_input[strcspn(new_input, "\n")] = '\0';
original = create_string(original, new_input);
break;
case 3:
int start, end;
printf("Start and end indices: ");
scanf("%d%d", &start, &end);
get_substring(original, start, end);
break;
case 4:
int del_start, del_length;
printf("Start index and length to delete: ");
scanf("%d%d", &del_start, &del_length);
delete_substring(&original, del_start, del_length);
break;
case 5:
int insert_index;
char insert[100];
printf("Insertion index and string: ");
scanf("%d%s", &insert_index, insert);
insert_substring(&original, insert_index, insert);
break;
case 6:
printf("Exiting...\n");
free(original.str);
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
```
在这个程序中,用户可以按照提示选择初始化、创建新的字符串、获取子串、删除子串或插入子串。注意,在实际应用中,你需要处理可能出现的错误情况,比如内存分配失败等。
阅读全文