c++ - “如何使用 C++ 将字符串的第一个和最后一个索引返回到 vector 中?

标签 c++ arrays string vector

这是 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;

谢谢大家!!

关于c++ - “如何使用 C++ 将字符串的第一个和最后一个索引返回到 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58139035/

相关文章:

C++ 'No matching function for call to' 模板

c++ - C++ 中的指针和 const

c - *p = array[i] 的效果?

ruby - 从字符串数组生成唯一的初始字符串

c++ - 在 dll 中使用 std::list 无法解析的外部符号

c++ - CodeBlocks SFML 音频库将不起作用

arrays - 是否有转置 3D 数组的 Fortran 函数?

javascript - 如何按时间戳对数组进行排序?

python - String.find 不返回任何值

python-3.x - str 对 csv 格式的响应