小程序 - 压缩字符串

时间:2016-03-21 14:06:26   收藏:0   阅读:169
/*
* Zip a string. For example, "aaabcc" => "3ab2c".
* You should directly update the input string.
*/
void strzip(char *str)
{
    int count;
    char *p, *idx, c;

    for (count = 0, p = idx = str; str[0]; str++)
        if (p[0] == str[0])
            count++;
        else {
            if (count > 1) {
                c = str[0];
                idx += sprintf(idx, "%d%c", count, p[0]);
                str[0] = c;
            } else
                *idx++ = p[0];
            p = str;
            count = 0;
        }

    if (p < str - 1)
        idx += sprintf(idx, "%d%c", count + 1, p[0]);
    else
        *idx++ = p[0];
    *idx = \0;
}

int main(void)
{
    char test1[20] = "aaabcc"; // => "3ab2c"
    char test2[20] = "aab"; // => "2ab"
    char test3[20] = "a"; // => "a"
    char test4[20] = ""; // => ""
    char test5[20] = "abcd"; // => "abcd"
    char test6[20] = "aaaaaaaaaaaaaaaab"; // => "16ab"

    strzip(test1);
    printf("%s\n", test1);
    strzip(test2);
    printf("%s\n", test2);
    strzip(test3);
    printf("%s\n", test3);
    strzip(test4);
    printf("%s\n", test4);
    strzip(test5);
    printf("%s\n", test5);
    strzip(test6);
    printf("%s\n", test6);
    return 0;
}

 

原文:http://www.cnblogs.com/brayden/p/5301511.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!