【问题标题】:Return index of last occurrence of a char in a constant array of chars返回字符常量数组中最后一次出现的字符的索引
【发布时间】:2017-01-17 00:59:41
【问题描述】:

我需要返回 const 字符数组中最后一次出现的字符。因此,如果我有一个 const 字符数组,即 ["helloe"] 并且我需要返回的 char 索引是 "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());
}

【问题讨论】:

  • 一个更简单的计划是返回第一次出现,但使用反向迭代器
  • 您的问题/疑问是什么?
  • size 会比 bob 更好。
  • 如果只想找到一个值,为什么还需要向量?

标签: c++ arrays for-loop indexing char


【解决方案1】:
std::vector<int> no;

// ...

no.push_back((int)i);

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

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

这没什么意义。您的意图似乎是从字符串末尾开始扫描(bob 是字符串的长度)。这将是一个合理的开始。但是,如果您的意图是从字符串的末尾开始并返回到i=0,您希望i 减少,而不是增加。此外,比较i&gt;bob 再次毫无意义。 i 的初始值为bob,表达式i&gt;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 而不是ints 在技术上更正确。

【讨论】:

  • 使用size_t 也是可以接受的(std::string 实际上就是这样做的)
  • 请注意size_t 如果您在循环中使用--i 会爆炸,例如降至0,因为它会再运行一次,而负数size_t 会造成一些非常糟糕的情况东西。还有auto 会怎么做?
【解决方案2】:

另一种解决方案是从末尾向后循环并在第一次出现字符时停止:

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;
}

【讨论】:

    【解决方案3】:

    带有反向迭代器的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';
    }
    

    【讨论】:

    • 此代码假定使用 C++14。对于早期版本,您可以直接使用std::reverse_iterator,也可以使用std::find_end()
    猜你喜欢
    • 2012-03-23
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 2019-05-28
    • 1970-01-01
    • 2011-07-26
    相关资源
    最近更新 更多