返回常量字符数组中字符最后出现的索引

Return index of last occurrence of a char in a constant array of chars

本文关键字:字符 索引 常量 数组 返回 最后      更新时间:2023-10-16

我需要返回字符常量数组中字符的最后一次出现。所以如果我有一个字符的const数组是["hello "]我需要返回的字符索引是"e"它将返回5。

//s is a const array of chars that equals ["helloe"]
// c is the char "e"
// I need to return the index of the last occurrence of e which is 5
int reverse_find_character(const char s[], char c){
    std::vector<int> no;
    size_t bob = strlen(s);
    size_t i;
    for (i=bob;i>bob;i++){
       if (s[i]==c){
           no.push_back((int)i);
       }
   return *max_element(no.begin(),no.end());
}
std::vector<int> no;
// ...
no.push_back((int)i);

为什么需要一个向量?你根本不需要向量。您不需要记住搜索字符的每一次出现。你只需要找到最后一个。

for (i=bob;i>bob;i++){

这没有什么意义。您的意图似乎是从字符串的末尾开始扫描(bob是字符串的长度)。这将是一个合理的开始。但是,如果您的意图是从字符串的末尾开始并返回i=0,则您希望i是递减的,而不是递增的。此外,i>bob的比较也没有意义。当i的初始值为bob时,表达式i>bob的求值为false,此循环将永远不会执行。

无论如何,这整件事真的比你想象的要简单得多:

  1. 开始从头到尾扫描字符串

  2. 每次看到要查找的字符时,将其索引保存在一个变量中

因此,在扫描结束时,该变量将是字符串中字符最后位置的索引,因为您是从开始到结束扫描它。

换句话说:

int reverse_find_character(const char s[], char c){
    int pos=-1;
    size_t i;
    for (i=0; s[i]; ++i)
       if (s[i] == c)
           pos = i;
    return pos;
}

注:您没有询问类型,但是在这种情况下,使用ssize_t而不是int s在技术上更正确。

另一种解决方案是从末尾开始向后循环,并在char:

第一次出现时停止。
int reverse_find_character(const char s[], char c){
    for (int i = strlen(s)-1; i>=0; --i)
        if (s[i] == c)
            return i;
    return -1;
}

带反向迭代器的std::find呢?然后使用std::distance获取索引。

#include <algorithm>
#include <iostream>
using namespace std;    
int main()
{
    const char str[] = "helloe";
    auto it = std::find(crbegin(str), crend(str), 'e');
    cout << std::distance(cbegin(str), (it + 1).base()) << 'n';
}