【发布时间】:2020-11-22 22:15:17
【问题描述】:
嗯,这是另一个经典的谜题……我的目标是取出字符串中每个单词的第一个字母,并将其放在该单词的末尾加上 -ay(猪拉丁语)。我设法改变了第一个词。但是我该如何进入下一个呢?我咨询了不同的来源、论坛,但我仍然卡住了......有什么提示吗? :) 可能类似于:pos = a.find(" ", pos +1)?见以下代码:
#include <iostream>
#include <string>
int main()
{
std::string a = "hello what is going on";
std::string b = "ay ";
std::size_t pos = a.find(" ");
int length = a.length();
std::string first = a.substr(0,1);
for (int i = 0; i <= length; i++)
{
if (pos != std::string::npos)
{
a.replace(pos, a.length(), first + b); //I guess I have to change sth. here.
} //Maybe a while-loop?
}
a.replace(0, 1, "");
std::cout << a; //Output: "ellohay"; **goal**: "ellohay hatway siay oingay noay"
}
【问题讨论】:
-
我会将字符串拆分为字符串向量,然后循环操作每个字符串
-
嗯,你已经知道大部分答案了。当你尝试类似
pos = a.find(" ", pos +1)时发生了什么? -
另外,Pig Latin 也不是那么简单。
-
@Igor Tandetnik:出现了这样的事情:ellohayhayhayhayhayhayhayhayhayhayh。 :)
-
@Thomas Sablik:我会试试的。由于我还没有使用矢量,因此需要阅读有关如何执行此操作的内容。