• C++(四)— 字符串、数字翻转3种方法


    1、使用algorithm中的reverse函数,string类型字符建议使用。

    #include <iostream>  
    #include <string>  
    #include <algorithm>  
    using namespace std;  
    
    int main()
    {
        string str;
        cin >> str;
    
        reverse(str.begin(), str.end());
    
        cout << str << endl;
        return 0;
    }
    #include<iostream>
    #include<stdio.h>
    #include<algorithm>
    #include<string>
    using namespace std;
    
    int main()
    {
        string str;
        cin >> str;
    
        //reverse(str.begin(), str.end());
        //自己实现,交换对应位置字符。
        int start = 0, end = str.size()-1;
        while (start < end)
        {
            swap(str[start++], str[end--]);
        }
        cout << str << endl;
    
        return 0;
    }

    2、使用string.h中的strrev函数,char类型字符建议使用。

       C++中有函数strrev,功能是对字符串实现反转,但是要记住,strrev函数只对字符数组有效,对string类型是无效的。

    #include <iostream>  
    #include <cstring>  
    using namespace std;  
      
    int main()  
    {  
        char s[]="hello";  
      
        strrev(s);  
      
        cout<<s<<endl;  
      
        return 0;  
    }  

    3、翻转句子单词序列

      例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。

    class Solution {
    public:
        string ReverseSentence(string str) {
            if(str.empty())
                return str;
            int start = 0,end = str.size()-1;
            reverse(str, start, end);
            start = 0;
            for(int i=0;i<str.size();++i)
            {
                if(str[i] == ' ')
                {
                    reverse(str, start, i-1);
                    start = i+1;
                }
            }
            reverse(str, start, str.size()-1);
            return str;
        }
        void reverse(string &str, int start, int end)
        {
            while(start < end)
                swap(str[start++], str[end--]);
        }
    };

    4、数字翻转

      123—>321,高位到地位,低位到高位。

    void reverse()
    {
        int n;
        int res = 0;
        cin >> n;
        while (n)
        {
            res = res * 10 + n % 10;
            n = n / 10;
        }
        cout << res << endl;
    }
  • 相关阅读:
    马云演讲稿
    马云演讲稿
    使用命令行+代理更新Android SDK
    GitHub 中国区前100 名技术专家
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
  • 原文地址:https://www.cnblogs.com/eilearn/p/9366938.html
Copyright © 2020-2023  润新知