将一个字符串插入至另一个源字符串的某个位置
将一个字符串插入至另一个源字符串的某个位置:
将一个字符串2插入到源字符串1中 第一次出现某字符的位置,并打印出形成的新串。
如果 字符串1中找不到输入的字符, 则显示“Not found!”并结束程序。
注:源字符串长度及待插入字符串长度不超过50
提示信息:
printf(“Input source string 1:\n”)
printf(“Input inserted string 2:\n”)
printf(“Input a letter to locate the index:\n”)
输出信息格式:
printf(“The new string is:%s”)
printf(“Not found!”)
测试样例1:
输入信息:
Input source string 1:
abcdecfg
Input inserted string 2:
---
Input the a letter to locate the index:
c
输出结果:
The new string is:ab*---*cdecfg
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void insert(char* a, int pos, char n) //创建一个插入单个字符函数
{
int i;
for (i = strlen(a);i >= pos;i--)
{
*(a + i + 1) = *(a + i);
}
*(a + pos) = n;
}
int main()
{
char str, s1[100], s2[100];
int i, pos, flag = 0;
printf("Input source string 1:\n");
scanf("%s", s1);
getchar();
printf("Input inserted string 2:\n");
scanf("%s", s2);
getchar();//吸收输入第二个字符串后的回车以防第三个输入把回车识别进去
printf("Input a letter to locate the index:\n");
scanf("%c", &str);
for (i = 0;s1[i];i++)
{
if (s1[i] == str)
{
pos = i;
flag = 1;
break;
} //通过找到字符的第一次出现而获取插入位置
}
if (flag)
{
for (i = 0;s2[i] != 0;i++)
{
insert(s1, pos + i, s2[i]);//通过反复调用插入单个字符函数而把整个字符串插入进去
}
printf("The new string is:%s", s1);
}
if (!flag)
printf("Not found!");
return 0;
}
有问题可向作者提出,多交流
该程序段使用C语言实现将一个字符串插入到另一个源字符串中指定字符首次出现的位置。如果找不到指定字符,则输出Notfound!。用户需输入源字符串1、待插入字符串2和定位字符。
2892

被折叠的 条评论
为什么被折叠?



