C++: Finding the last occurence of a char in a string
I've been working on this for nearly a couple hours. I believe my solution
to be logically correct, however I don't get the desired output. For
example, suppose I want to find the last time the character "h" appears in
this string: "hlhhhlh" (6 if we start from 0).
My program compiles, but it doesn't work. This code only finds out when
the first occurence of "h" from a char element.
#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;
}
}
}
}
No comments:
Post a Comment