"如何使用C++将字符串的第一个和最后一个索引返回到向量中?

"How do I return the first and last index of a string, into a vector, with C++?

本文关键字:返回 索引 最后一个 向量 第一个 何使用 C++ 字符串      更新时间:2023-10-16

这是来自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.

知道了!!

vector<int> arr;
arr[0] = word.find_first_of(c);
arr[1] = word.find_last_of(c);
return arr;

谢谢大家!!