HJ106 字符逆序
#include <iostream>
#include <string>
void swap(std::string& s, int i, int j) {
int len = s.length();
if (i != j && (i >= 0 && i < len) && (j >= 0 && j < len)) {
char tmp = '0';
tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
}
void reverse(std::string& s) {
int len = s.length();
for (int i = 0; i < (len / 2); ++i) {
swap(s, i, len - i - 1);
}
}
int main() {
std::string in;
while (getline(std::cin, in)) {
reverse(in);
std::cout << in << std::endl;
}
return 0;
}
解题思路:
难点1:仔细!
知识点:
知识点1:C++ reverse函数的用法;
#include <algorithm>
#include <string>
using namespace std;
int main() {
string str = "hello world , hi";
reverse(str.begin(), str.end()); //str结果为ih , dlrow olleh
vector<int> v = {5, 4, 3, 2, 1};
reverse(v.begin(), v.end()); //容器v的值变为1, 2, 3, 4, 5
}