프로그래밍 언어/C++
[C++] 문자열 뒤집는 방법
ShovelingLife
2024. 11. 13. 18:05
1. reverse() 함수 <algorithm>
#include <algorithm>
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str = "abcd";
reverse(str.begin(), str.end());
cout<<"\n"<<str;
return 0;
}
1.5 reverse iterator 사용
string str, rstr;
cin >> str;
rstr.assign(str.rbegin(), str.rend());
2. strrev() 함수 <cstring>
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char str[] ="abcd";
strrev(str);
cout<<"\n"<<str;
return 0;
}
3. for문 사용
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str="abcd";
int i;
for(i = str.length() - 1; i >= 0; i--)
{
cout<<str[i];
}
return 0;
}
4. 투포인터 사용
#include <iostream>
#include <string>
void reverseString(std::string& str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
std::swap(str[left], str[right]);
left++;
right--;
}
}
int main() {
std::string str = "Hello, World!";
reverseString(str);
std::cout << str << std::endl;
return 0;
}
5. 재귀함수
#include <iostream>
#include <string>
std::string reverseStringRecursive(const std::string& str) {
if (str.length() <= 1) {
return str;
} else {
return reverseStringRecursive(str.substr(1)) + str[0];
}
}
int main() {
std::string str = "Hello, World!";
std::string reversedStr = reverseStringRecursive(str);
std::cout << reversedStr << std::endl;
return 0;
}