返回常量字符数组中字符最后出现的索引
Return index of last occurrence of a char in a constant array of chars
我需要返回字符常量数组中字符的最后一次出现。所以如果我有一个字符的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
,此循环将永远不会执行。
无论如何,这整件事真的比你想象的要简单得多:
开始从头到尾扫描字符串
每次看到要查找的字符时,将其索引保存在一个变量中
因此,在扫描结束时,该变量将是字符串中字符最后位置的索引,因为您是从开始到结束扫描它。
换句话说:
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';
}
相关文章:
- 将转换字符键入 int 以用作向量C++的索引
- 查找字符在两个索引之间出现的次数
- *无符号字符中的索引值
- C++ char 类查找字符索引
- int 数组,但索引是字符?
- 为什么在 c++ 中索引字符串会发出隐式转换警告?
- 根据字符获取数组的索引
- CPP:如何获取字符的最后一个索引
- 如何计算 3d 数组中的索引值在内存中的位置?如何计算字符**中的索引值在内存中的位置?
- 将特定索引处的字符数组内容与字符文字 - cpp 进行比较
- 为字符串中的每个字符(不是字符位置!)分配唯一的索引
- 通过字符串的字符对整数数组进行索引
- 从给定索引返回子字符字符串的函数
- 在C 字符串中,为什么在最后一个字符之后,通过索引和()访问索引时行为是不同的
- 是否可以使用字符串或字符索引数组
- 如何使该程序在数组中打印搜索字符的索引,否则将找不到它
- 如何在 C++ 的字符串中打印从一个索引到另一个索引的字符范围
- 为什么在使用字符索引数组时会出现这种不同的行为
- 从 1 中创建新的字符 * 作为参数,元素位于 2 个索引之间
- 字符串下标超出范围.我不知道如何使用字符索引数组,所以我使用了(无符号整数),但它不起作用