本文实例讲述了C语言字符串原地压缩的实现方法,对于学习字符串操作的算法设计有不错的借鉴价值。分享给大家供大家参考。具体方法如下:
字符串原地压缩示例: "eeeeeaaaff"压缩为"e5a3f2"
具体功能代码如下:
/* * Copyright (c) 2011 alexingcool. All Rights Reserved. */#include <iostream>#include <iterator>#include <algorithm>using namespace std;char array[] = "eeeeeaaaff";char array2[] = "geeeeeaaaffg";const int size = sizeof array / sizeof *array;const int size2 = sizeof array2 / sizeof *array2;void compression(char *array, int size){ int i = 0, j = 0; int count = 0; while(j < size) { count = 0; array[i] = array[j]; while(array[j] == array[i]) { count++; j++; } if(count == 1) { i++; } else { array[++i] = '0' + count; ++i; } } array[i] = 0; }void main(){ compression(array, size); cout << array << endl; compression(array2, size2); cout << array2 << endl;}
相信本文所述对大家C程序算法设计的学习有一定的借鉴价值。
新闻热点
疑难解答
图片精选