代码改变世界

一道有趣的字符串部分转逆算法题

2013-10-21 23:10  Ross Wang  阅读(400)  评论(0编辑  收藏  举报

题目要求

给定字符串,将字符串中每个单词中的连续字符转逆,数字保持不变,比如

输入:ab12cd 34 jkl897

输出:ba12dc 34 lkj897

无标点符号。

函数原型:void HandleStr(char * result, const char * src)

直接代码:

#include <cstdio>

/******************
给定字符串,将字符串中每个单词中的连续字符转逆,数字保持不变,比如
输入:ab12cd 34 jkl897
输出:ba12dc 34 lkj897
无标点符号。
函数原型:void HandleStr(char * result, const char * src)
******************/
void HandleStr(char * result, const char * src)
{
    //进行合法性验证
    if(src == NULL || src[0] == '\0')
    {
        *result = '\0';
        return;
    }

    //标记每次遇到连续字符的第一个字符位置
    int lastWordPos = -1;
    char currentChar;
    int step = 0;
    for(; *(src+step) != '\0'; ++step)
    {
        currentChar = *(src+step);
        result[step] = currentChar;
        if((currentChar >= 'a' && currentChar <= 'z') ||
            (currentChar >= 'A' && currentChar <= 'Z')
            )
        {
            if(lastWordPos == -1)
                lastWordPos = step;
        }
        else if(currentChar >= '0' && currentChar <= '9' ||
            currentChar == ' ' || currentChar == '\0')
        {
            if(lastWordPos != -1)
            {
                char tempChar;
                for(int pos = 0; (lastWordPos + pos) <=(step-1-pos); ++pos)
                {
                    tempChar = result[lastWordPos + pos];
                    result[lastWordPos + pos] = result[step-1-pos];
                    result[step-1-pos] = tempChar;
                }
                lastWordPos = -1;
            }
        }
    }
    //字符串中最后一个单词也可能是字符,也需要进行转逆
    if(lastWordPos != -1)
    {
        char tempChar;
        for(int pos = 0; (lastWordPos + pos) <=(step-1-pos); ++pos)
        {
            tempChar = result[lastWordPos + pos];
            result[lastWordPos + pos] = result[step-1-pos];
            result[step-1-pos] = tempChar;
        }
        lastWordPos = -1;
    }
    result[step] = '\0';
}
int main()
{
    //测试数据
    char * src[6] = 
    {
        "This is the first test",
        "12345678",
        "8971 6489",
        "Oct1 is celebrated by more than 1.3billion peoples",
        "abcd1234 efgh56ijk78 897",
        ""
    };

    for(int i = 0; i<6; i++)
    {
        //定义一个相对于测试数据足够大的字符数组用来输出
        char output[100];
        HandleStr(output,src[i]);
        printf("Original string: %s\n",src[i]);
        printf("Handled string : %s\n",output);

    }

    return 0;
}

输出结果:

Original string  : This is the first test
Handled string : sihT si eht tsrif tset
Original string  : 12345678
Handled string : 12345678
Original string  : 8971 6489
Handled string : 8971 6489
Original string  : Oct1 is celebrated by more than 1.3billion peoples
Handled string : tcO1 si detarbelec yb erom naht 1.3noillib selpoep
Original string  : abcd1234 efgh56ijk78 897
Handled string : dcba1234 hgfe56kji78 897
Original string  :
Handled string :