倒置字符串

题目描述

将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I

输入描述:

每个测试输入包含1个测试用例: I like beijing. 输入用例长度不超过100

输出描述:

依次输出倒置之后的字符串,以空格分割

示例1
**输入:**00

I like beijing.

输出:

beijing. like I

解题思路一:
1.字符串整体先逆置
2.以空格为分隔符为一个子串,分别逆置
3.输出逆置后的str

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

int main()
{
    string str;
    //输入的字符串有空格,不能直接用cin
    getline(cin,str);
    //先把一整个字符串逆置
    reverse(str.begin(), str.end());
    
    auto start = str.begin();
    while(start < str.end())
    {
    	//startend设置为一样
        auto end = start;
        
        //遍历,只要没有遇到空格,end++
        while(end < str.end() && *end != ' ')
            end++;
            
         //end遇到空格,逆置startend之间的字符串
        reverse(start,end);
        
        //子串逆置后,把start置为下一个子串的起始位置,即end+1
        if(end != str.end())
            start = end + 1;
        else
            start = end;    //end = str.end()了,则走到了最后,逆置也不变
    }
    cout << str << endl;
    return 0;
}

解题思路二:
直接利用cin>>s接收输入,遇到空格就结束了,自然就分割开了每个单词,其次将每次接收到的单词拼接到之前串的前面就逆置过来了

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string str1,str2;
    cin>>str2;
    //while循环,可以一直输入多个字符串,相当于每次更新str2
    while(cin>>str1)
    {
        str2 = str1 + " " + str2;
    }
    cout << str2 << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值