本文實(shí)例講述了C語(yǔ)言字符串原地壓縮的實(shí)現(xiàn)方法,對(duì)于學(xué)習(xí)字符串操作的算法設(shè)計(jì)有不錯(cuò)的借鑒價(jià)值。分享給大家供大家參考。具體方法如下:
字符串原地壓縮示例: "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;}
相信本文所述對(duì)大家C程序算法設(shè)計(jì)的學(xué)習(xí)有一定的借鑒價(jià)值。
新聞熱點(diǎn)
疑難解答
圖片精選