字符串压缩--思路总结

 

 相关回顾

1.关于puts函数的用法 

https://blog.csdn.net/qq_41704436/article/details/104711105

2.字符串输入输出 

字符串的输入输出---要点总结,详见https://blog.csdn.net/qq_41704436/article/details/104699255

3.经典--字符串输入输出方法

https://blog.csdn.net/qq_41704436/article/details/104699255 

4.常用的字符串函数

https://blog.csdn.net/qq_41704436/article/details/104734740

字符串压缩

1.字符串压缩---效果

字符+重复的次数(当字符不重复时不显示数字)

2.字符串压缩---思路

  1. while(i<strlen(str))
    1. 保证游标不溢出
    2. 当i==strlen(str)----跳出这层循环,字符串压缩结束
  2. 输出str[i]----字符压缩的结构组成
  3. while(str[i]==str[i+1])
    1. 初始化的count为1,切记!!!(游标所在位置就是一个字符了)
    2. 当游标所在位置and下一位置,相同时,count++;i++;
    3. 当下一个and下下个,相同时,仍在循环内。正常计数!
  4. str[i] != str[i+1]----跳出这层循环
    1. 既然两者不相等,往下走----i++;
    2. if(count!=1)----说明此时要输出重复的数字,最后要count=1(置初始值)
      1. count==1----不用输出(规则要求)

 3.代码1

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
	char str[50];
	int i=0,count=1; 
	printf("请输入字符串:\n");
	gets(str);
	printf("显示字符串:\n");
	puts(str);
	printf("字符串的长度为:%d\n",strlen(str));
	
	//字符串压缩
	printf("字符串压缩:\n"); 
	 while(i<strlen(str))
	 {
	 	printf("%c",str[i]);
 		while(str[i]==str[i+1])
 		{
		 	count++;
		 	i++;
		 }
		 i++;
		 if(count!=1)
		 {
 			printf("%d",count);
 		}
		 count=1;
 	} 
	return 0;
} 

4.注:也可用指针

void CompressStr(char* str)
{
	puts("字符串压缩。。。");
	int count=1,i=0;
	while(i<strlen(str))
	{
		printf("%c",*(str+i));
		while(*(str+i)==*(str+i+1))
		{
			count++;
			i++;
		}
		if(count!=1)
		{
			printf("%d",count);
		}
		/*切记!!!
		  1.count初始化 
		  2.i++;循环 
		*/ 
		count=1;
		i++;
	}
	puts("\n完成。。。");
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Larry Chow

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值