编程之法 1.3 字符串反转

单词反转


  输入一个英文句子,反转句子中单词的顺序,要求单词内字符的顺序不变,句子中单词以空格隔开。为简单期间,标点符号和普通字符一样处理。例如输入“I am a student.”,则输出“student. a am I”。


代码思想


  • 先进行整体反转
    • 将”I am a student.”翻转为”.tneduts a ma I”
  • 再将字符串中每个单词进行反转(可以通过空格进行分割)
    • 通过begin()+end()进行划分

具体实现代码


//1.3 单词反转
#include <iostream>
using namespace std;
void reverseStr(string & str)
{
    //此处先进行整体反转
    reverse(str.begin(), str.end());
    auto iterFront = str.begin();
    int posBegin = 0, posEnd = str.find(' ', 0);
    //跳出条件为 没有找到空格
    while (posEnd!=-1)
    {
        //每个单词进行一次反转
        reverse(iterFront+posBegin, iterFront + posEnd);
        //向后再查找空格
        posBegin=posEnd+1;
        posEnd = str.find(' ', posBegin + 1);
    }


}
void main()
{
    string str = "I am a student.";
    reverseStr(str);
    cout << str.c_str() << endl;
}

猜你喜欢

转载自blog.csdn.net/m0_37316917/article/details/79936018