本文实例讲述了C语言字符串原地压缩的实现方法,对于学习字符串操作的算法设计有不错的借鉴价值。分享给大家供大家参考。具体方法如下:
字符串原地压缩示例: "eeeeeaaaff"压缩为"e5a3f2"
具体功能代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
/*
* 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程序算法设计的学习有一定的借鉴价值。