1.题目
编写一个函数,利用指针在字符串s中的指定字符前面和后面均插入标记字符。若指定字符连续出现则只需要在连续的两端插入各一次标记字符。指定字符和标记字符均从键盘输入。
要求:子函数char *InsertStr(char *s,char t,char c)
【输入形式】
输入主串s,输入指定字符t,输入标记字符c.
【输出形式】
输出插入后字符串
【样例输入1】abbcabcde
b
#
【样例输出1】a#bb#ca#b#cde
2.完整代码
#include <stdio.h>
#include <string.h>
#define N 100
char result[N];
char* InsertStr(char *s,char t, char c)
{
int length = strlen(s);
int i = 0;
int count = 0; //result中元素的个数
while(i<length)
{
if(i==0)
{
if(s[i] == t)
{
result[count++] = c;
}
}
else
{
if((s[i]==t && s[i-1]!=t)||(s[i]!=t && s[i-1]==t))
{
result[count++] = c;
}
}
result[count++] = s[i];
i++;
}
if(s[length-1]==t){
result[count++] = c;
}
result[count]='\0';
return result;
}
int main()
{
char s[N];
char t;
char c;
gets(s);
t=getchar();
scanf("\n");
c=getchar();
char *p = InsertStr(s,t,c);
puts(p);
return 0;
}