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

时间:2016-09-09 00:26:35

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

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

3 个答案:

答案 0 :(得分:1)

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. 每当您看到要搜索的字符时,请将其索引保存在变量中。

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

    换句话说:

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

    P.S。您没有询问类型,但在此上下文中使用ssize_t代替int更为技术正确。

答案 1 :(得分:1)

另一个解决方案是从结尾向后循环并在第一次出现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;
}

答案 2 :(得分: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';
}