Reverse string in c++

 

由於我高階語言寫習慣了,在python中翻轉字串也就是一行的事

my_string[::-1]

但在C語言中卻不是如此,最簡單的寫法就是創建一個新的string然後再從後面慢慢地加入要的字元

 

#include <iostream>
using namespace std;
int main() {
string greeting = "Hello!";
string new_greeting;
for(int n = greeting.length()-1; n >= 0; n--){
new_greeting.push_back(greeting[n]);
}
cout<<"Original string: "<< greeting << endl;
cout<<"New reversed string: "<< new_greeting << endl;
}

 

但還有更有效率的寫法,建立一個新的字串需要花費額外的記憶體空間,更好的方法是在同一個字串中一直做前後調換的動作就好

#include <iostream>
using namespace std;
int main() {
string greeting = "Hello!";
int len = greeting.length();
int n=len-1;
for(int i=0;i<(len/2);i++){
char temp = greeting[i];
greeting[i] = greeting[n];
greeting[n] = temp;
n = n-1;
}
cout<<greeting<<endl;
}

 

關於置換這個動作在C++裡面可以用簡便的swap置換

#include <iostream>
using namespace std;
int main() {
string greeting = "Hello!";
int len = greeting.length();
int n=len-1;
for(int i=0;i<(len/2);i++){
swap(greeting[i],greeting[n]);
n = n-1;
}
cout<<greeting<<endl;
}

最簡便的寫法是使用內建的reverse 函數,但刷了幾題的結果告訴我這種function要越少用越好,因為用這種方式寫會過度依賴內建的函數導致換成低階語言就不會寫了

#include <iostream>
//The library below must be included for the reverse function to work
#include<bits/stdc++.h>
using namespace std;
int main() {
string greeting = "Hello";
//Note that it takes the iterators to the start and end of the string as arguments
reverse(greeting.begin(),greeting.end());
cout<<greeting<<endl;
}

https://www.educative.io/blog/reverse-string-javascript-cpp-python

https://www.educative.io/edpresso/how-to-reverse-a-string-in-cpp

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments