#include <iostream> #include <string> using namespace std; class Solution { public: /** * 大小写转换函数(按引用修改字符串) */ void transAtoa(string& s) { // 改为引用传递 if(s.empty()){ return ; } for (char& c : s) { if (c >= 'A' && c <= 'Z') { c += 32; // 大写转小写 } else if (c >= 'a' && c <= 'z') { c -= 32; // 小写转大写 } // 其他字符(如空格)保持不变 } } string trans(string s, int n) { string res; string t; for (int i = 0; i < n; i++) { if (s[i] != ' ') { t.push_back(s[i]); } else { transAtoa(t); // 转换大小写 res = t + " " + res; // 单词逆序拼接 t.clear(); } } // 处理最后一个单词(如果存在) if (!t.empty()) { transAtoa(t); res = t + " " + res; } // 移除末尾多余的空格 if (!res.empty()) { res.pop_back(); } if(s[n-1]==' '){ res = ' ' + res ; } return res; } };
要对string做倒序操作,使用字符串拼接来进行,注意末尾空格处理