zoukankan      html  css  js  c++  java
  • 编程之法 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;
    }
    https://github.com/li-zheng-hao
  • 相关阅读:
    Spring MVC的常用注解(一)
    Spring MVC接口实例
    MVC模式和Spring MVC初识
    Hbase数据结构和shell操作
    Hbase的安装和配置
    ZooKeeper安装、配置和使用
    hadoop的安装和配置
    VMware Workstation安装CentOS 7和开发环境
    Java基础-内部类
    SSM三大框架整合
  • 原文地址:https://www.cnblogs.com/lizhenghao126/p/11053691.html
Copyright © 2011-2022 走看看