"三步反转"处理字符串

istringstream、ostringstream、stringstream 类介绍 .

http://www.cnblogs.com/gamesky/archive/2013/01/09/2852356.html

下面的输入处理比较常用:

#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>

using namespace std ;

int main()
{
    freopen("in.txt", "r", stdin);
    string str, line;
    while(getline(cin, line))
    {
        istringstream stream(line);
        while(stream>>str)
            cout<<str.c_str()<<endl;
    }   
    return 0;
}

输入
I am a student.
输出
I
am
a
student.

C++编程中关于输入的一些函数
cin、cin.get()、cin.getline()、getline()、gets()等函数的用法:http://www.cnblogs.com/wanghao111/archive/2009/09/05/1560822.html

c++中string类的详解
http://blog.csdn.net/yzl_rex/article/details/7839379

三步反转

#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>

using namespace std ;

// 反转字符串
string reverse_string(string s)
{
    int len = s.length();
    int from = 0 ;
    int to = len-1;
    while(from < to)
    {
        char tmp = s[from];
        s[from] = s[to];
        s[to] = tmp;
        from ++ ;
        to --;
    }
    return s;
}
int main()
{
    //freopen("in.txt", "r", stdin);
    string str, line;
    while(getline(cin, line))
    {
        string rs = "";
        istringstream stream(line);
        int words_num = 0;
        while(stream>>str)
        {
            if(words_num == 0)
                rs += reverse_string(str) ;
            else
                rs += " " + reverse_string(str);
            words_num ++ ;
        }
        cout << reverse_string(rs) << endl ;
    }   
    return 0;
}

输入1
I am a student.
输出1
student. a am I

输入2
How are you
输出2
you are How

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值