【发布时间】:2020-01-28 01:04:46
【问题描述】:
这是 Edabit 的一个编码问题。我正试图专注于我在 C++ 中解决问题的技能。
问题是从字符串中返回字符的第一个和最后一个索引。对于std :: string word(第一个参数)中的char c(第二个参数)的每个实例,我认为我需要将(char c)与push_back一起推送到一个空字符串并从该空字符串返回第一个和最后一个索引。或者我可以简单地使用从原始字符串中提取字符的第一个和最后一个实例吗
(例如:std::string word.being())?
到目前为止,我已经在下面包含了一些代码。我只是坚持如何用语法实现我的想法。我认为我的想法是正确的,但不知道如何去做。我不想要一个确切的答案,只是一个关于下一步做什么的指南。
std::vector<int> charIndex(std::string word, char c) {
std::string newWord = "";
for(int i = 0; i < word.size(); ++i){
std::string size.push_back[i] = newWord;
//for every instance of char c in std::string word, I need to
//push that (char c) to empty string and return first and last index
if(newWord[i] == )
}
}
这些是预期结果的示例:
charIndex("circumlocution", "c") ➞ [0, 8]
The first "c" has index 0, the last "c" has index 8.
charIndex("happy", "h") ➞ [0, 0]
Only one "h" exists, so the first and last index is 0.
【问题讨论】:
-
所以你知道std::find
-
这个赋值实际上是两行 C++ 代码,使用
std::find并将[first, last]结果放入类似std::pair<int, int>的东西中。不需要循环、堆栈或任何类似的东西。 -
我想您可能会发现
std::string::find_first_of很有用。如果您阅读链接文档页面的底部,您会找到其他有用实用程序的链接,这些实用程序可用于解决问题的其他部分。