我一直在为此工作近几个小时。我相信我的解决方案在逻辑上是正确的,但是我没有得到期望的输出结果。例如,假设我想查找字符串上最后一次出现字符“h”:“hlhhhlh”(如果我们从0开始,则为6)。C++:查找字符串中字符的最后一次出现
我的程序编译,但它不工作。此代码仅在char元素中第一次出现“h”时才会发现。
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int getIndex(vector<char> arr, char t);
int main()
{
vector<char> myArr(0);
myArr.push_back('l');
myArr.push_back('l');
myArr.push_back('l');
myArr.push_back('hlhh');
int i = getIndex(myArr, 'h');
cout << i << endl;
}
int getIndex(vector<char> myArr, char t)
{
int n=0, m=0, count=0;
string y,s;
vector<string> arr(0);
for(int i =0; i < myArr.size(); i++)
{
stringstream st;
st << myArr[i];
st >> y;
arr.push_back(y);
}
stringstream ss;
ss << t;
ss >> s;
for(int i=0; i < arr.size(); i++)
{
if(arr[i] == "h")
{
n++;
}
else if(arr[i] == "l")
{
m++;
}
}
for(int i=0; i< arr.size(); i++)
{
if(arr[i]==s)
{
count++;
if(count == n)
{
return i;
}
else if(count == m)
{
return i;
}
}
}
}
“近几个小时”?那是什么意思?不是一对夫妇,就这样,50分钟? –
使用'std :: string'并调用'find_last_of()'会更好? – billz
你为什么不调试你的程序?这真的很有帮助。 – dare