反转字符串

作者在 2012-05-17 23:34:47 发布以下内容
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    //源字符串
    char str[100];
    cin.get(str, 100);
    
    //申请目标字符串的空间
    size_t strLen = strlen(str);
    char *des = new char[strLen + 1];

    //源字符串上一次空格的位置
    size_t lastIndex = 0;

    for (size_t i = 0; i <= strLen; ++i)
    {
        if (str[i] == ' ' || str[i] == '\0')
        {
            size_t desIndex = strLen - i;
            size_t k = 0;

            for (size_t j = lastIndex; j < i; ++j, ++k)
            {
                des[desIndex + k] = str[j];
            }

            des[desIndex + k] = ' ';
            lastIndex = i + 1;
        }
    }
    des[strLen] = '\0';

    cout << des << endl;
    delete []des;
    return 0;
}
 
默认分类 | 阅读 1583 次
文章评论,共0条
游客请输入验证码
浏览31025次