我试图反转字符串中的单词而不会对标点符号产生任何影响。 这是我目前的代码:
#include<iostream>
#include<string>
using namespace std;
string ReverseString(string str, int len)
{
string trans;
for(int i=0;i<len;i++)
trans+=str.substr(len-i-1,1);
return trans;
}
int main()
{
string original;
string trans;
cout << "input: ";
getline(cin,original);
trans=ReverseString(original,original.size());
cout << "out: " ;
cout<<trans<<endl;
return 0;
}
预期行为:
输入:欢迎来到AC,CVB!
预期输出:emocleW ot CA,BVC!
观察到的行为:
输入:欢迎来到AC,CVB!
输出:!BVC,CA ot emocleW
答案 0 :(得分:0)
只需对单词进行一段时间循环并将其反转而不是整行:
string word;
while(your_end_condition)
{
cin >> word; // this takes one word at a time
cout << ReverseString(word, word.size()) << " ";
}
如果您不想使用cin
,可以使用原始字符串制作字符串流答案 1 :(得分:0)
这样:
#include <iostream>
#include <string>
#include <regex>
void myReplace(std::string& str,
const std::string& oldStr,
const std::string& newStr)
{
std::string::size_type pos = 0u;
while((pos = str.find(oldStr, pos)) != std::string::npos)
{
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
std::string reverWords(const std::string& str)
{
auto inp{str};
auto out{str};
std::regex rgx("[a-zA-Z]+");
std::smatch res;
while(regex_search(inp, res, rgx))
{
std::string s{res[0]};
std::reverse(s.begin(), s.end());
myReplace(out, std::string{res[0]}, s);
inp = res.suffix();
}
return out;
}
int main(int /*argc*/, char* argv[])
{
std::string str = "Welcome to AC, CVB!";
std::cout << reverWords(str);
return 0;
}