编写程序实现: 输入字符串及准备删除的字符位置和个数, 使用自编函数 char* str_delete( char *s, int v, int w)从字符串s的第v个字符开始删除w个字符, 将处理后的字符串首地址以函数返回值返回并输出显示处理后的字符串。c语言
时间: 2024-12-14 21:20:06 浏览: 27
在C语言中,你可以编写一个如下的`str_delete`函数来实现这个功能:
```c
#include <stdio.h>
#include <string.h>
// 自定义函数:删除字符串s指定位置和数量的字符
char* str_delete(char* s, int v, int w) {
if (v < 0 || v >= strlen(s) || w <= 0) {
printf("错误:删除的位置或数量无效。\n");
return NULL; // 如果输入有误,返回NULL表示失败
}
// 创建一个新的字符串,用于存储处理后的结果
size_t new_length = strlen(s) - w;
char* new_s = (char*) malloc(new_length + 1); // 分配新的内存空间
if (!new_s) {
printf("内存分配失败。\n");
return NULL;
}
// 复制原始字符串到新字符串,跳过删除的部分
strncpy(new_s, s, v);
strncpy(&new_s[v], s + v + w, new_length);
// 结尾添加'\0'
new_s[new_length] = '\0';
// 返回处理后的字符串地址
return new_s;
}
int main() {
char input[100];
printf("请输入字符串:");
fgets(input, sizeof(input), stdin); // 防止末尾多读取换行符
input[strcspn(input, "\n")] = '\0'; // 清理末尾的换行符
int delete_pos, num_to_del;
printf("请输入删除的起始位置和字符个数:");
scanf("%d %d", &delete_pos, &num_to_del);
char* result = str_delete(input, delete_pos, num_to_del);
if (result != NULL) {
printf("处理后的字符串:%s\n", result);
free(result); // 释放新分配的内存
} else {
// 打印错误信息并结束
return 1;
}
return 0;
}
```
当你运行此程序时,它会提示用户输入字符串、删除位置和字符数,然后将删除指定位置和数量的字符后得到的新字符串显示出来。如果删除操作无效或者内存分配出现问题,相应的错误消息会被打印。
阅读全文
相关推荐


















