为了能到远方,脚下的每一步都不能少.|

Dancing-Pierre

园龄:1年10个月粉丝:3关注:0

[C语言]压缩字符串并添加标记字符

[C语言]压缩字符串并添加标记字符

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;
}

3、截图

在这里插入图片描述

本文作者:Dancing-Pierre

本文链接:https://www.cnblogs.com/wyc-1009/p/17548017.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Dancing-Pierre  阅读(8)  评论(0编辑  收藏  举报  
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起