使用C语言定义一个字符串数组使其具有如下功能:1 输入一个字符串原样输出;2 对输入字符串统计字符个数;3 查找某个字符在字符串中第一次出现的位置;4 在字符串的指定位置插入一个字符; 5 删除字符串中的某个字符; 6 指定字符串从某位置开始由某个字符替换;7 将字符串中的某个字符替换成指定字符如把所有的字符a替换成c。
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int main() {
char str[MAX_LEN];
int len;
char c, new_c;
int pos;
int replace_len;
// 输入一个字符串,原样输出
printf("请输入一个字符串:");
fgets(str, MAX_LEN, stdin);
printf("原样输出:%s", str);
// 统计字符个数
len = strlen(str) - 1; // 减一是因为 fgets 会自动在输入末尾加上一个换行符
printf("字符个数:%d\n", len);
// 查找某个字符在字符串中第一次出现的位置
printf("请输入要查找的字符:");
scanf("%c", &c);
getchar(); // 读取多余的换行符
char *pos_ptr = strchr(str, c);
if (pos_ptr == NULL) {
printf("未找到该字符\n");
} else {
pos = pos_ptr - str;
printf("该字符第一次出现的位置:%d\n", pos);
}
// 在字符串的指定位置插入一个字符
printf("请输入要插入的字符:");
scanf("%c", &new_c);
getchar(); // 读取多余的换行符
printf("请输入要插入的位置:");
scanf("%d", &pos);
getchar(); // 读取多余的换行符
if (pos < 0 || pos > len) {
printf("插入位置不合法\n");
} else {
// 先将原字符串中 pos 及其之后的字符后移一位,然后再插入新字符
for (int i = len; i >= pos; i--) {
str[i + 1] = str[i];
}
str[pos] = new_c;
printf("插入后的字符串:%s", str);
}
// 删除字符串中的某个字符
printf("请输入要删除的字符:");
scanf("%c", &c);
getchar(); // 读取多余的换行符
pos_ptr = strchr(str, c);
if (pos_ptr == NULL) {
printf("未找到该字符\n");
} else {
// 先将原字符串中 pos 及其之后的字符前移一位,然后再删除最后一位
pos = pos_ptr - str;
for (int i = pos; i < len; i++) {
str[i] = str[i + 1];
}
str[len] = '\0';
printf("删除后的字符串:%s", str);
}
// 指定字符串从某位置开始由某个字符替换
printf("请输入要替换的字符:");
scanf("%c", &c);
getchar(); // 读取多余的换行符
printf("请输入要替换成的字符:");
scanf("%c", &new_c);
getchar(); // 读取多余的换行符
printf("请输入要替换的起始位置:");
scanf("%d", &pos);
getchar(); // 读取多余的换行符
if (pos < 0 || pos >= len) {
printf("起始位置不合法\n");
} else {
// 从 pos 开始遍历字符串,将 c 替换成 new_c
while (pos < len) {
if (str[pos] == c) {
str[pos] = new_c;
}
pos++;
}
printf("替换后的字符串:%s", str);
}
// 将字符串中的某个字符替换成指定字符
printf("请输入要替换的字符:");
scanf("%c", &c);
getchar(); // 读取多余的换行符
printf("请输入要替换成的字符:");
scanf("%c", &new_c);
getchar(); // 读取多余的换行符
pos_ptr = strchr(str, c);
if (pos_ptr == NULL) {
printf("未找到该字符\n");
} else {
replace_len = strlen(str) - (pos_ptr - str); // 需要被替换的字符序列的长度
// 先将原字符串中 pos 及其之后的字符后移,然后再将新字符序列插入到 pos 处
pos = pos_ptr - str;
for (int i = len; i >= pos + replace_len; i--) {
str[i + 1 - replace_len] = str[i];
}
for (int i = pos; i < pos + replace_len; i++) {
str[i] = new_c;
}
printf("替换后的字符串:%s", str);
}
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/eezV 著作权归作者所有。请勿转载和采集!