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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM