1、题目
小科最近在研究字符串压缩标记问题,他想在给定的字符串的指定字符前面插入标记字符,若指定字符连续出现则需要把连续的字符压缩为1个字符加出现的次数,指定字符和标记字符均从键盘输入。请你帮他解决这个需求吧。
【输入形式】输入主串 s(长度小于100),输入指定字符 t,输入标记字符 c。
【输出形式】输出插入后字符串
样例1:
输入:
abbcabcde
b
*
输出:
a* b2ca* bcde
样例2:
输入:
abbcbbbe
b
c
输出:
acb2ccb3e
2、完整代码
#define _CRT_SECURE_NO_WARNINGS // Visual Studio版本太新需加上
#include <stdio.h>
#define N 100
char res[N];
// 压缩字符串
int Compress(char* arr)
{
int i = 0;
int j = 0;
int cout = 1;
while (arr[i] != '\0')
{
if (arr[i] == arr[i + 1])
{
cout++;
}
else
{
if (cout == 1) {
arr[j++] = arr[i];
}
else if (cout != 1) {
arr[j++] = arr[i];
arr[j++] = cout + '0';
}
cout = 1;
}
i++;
}
arr[j] = '\0';
}
//添加标记字符
char* InsertStr(char* s, char t, char c)
{
int length = strlen(s);
int i = 0;
int count = 0;
while (i < length)
{
if (s[i] == t)
{
res[count++] = c;
}
res[count++] = s[i];
i++;
}
if (s[length - 1] == t) {
res[count++] = c;
}
res[count] = '\0';
return res;
}
int main()
{
char a[100], b, c;
gets(a);
Compress(a);
b = getchar();
scanf("\n");
c = getchar();
char* p = InsertStr(a, b, c);
puts(p);
return 0;
}