2013-08-31 396 views
-1

我一直在为此工作近几个小时。我相信我的解决方案在逻辑上是正确的,但是我没有得到期望的输出结果。例如,假设我想查找字符串上最后一次出现字符“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; 
      } 
     } 
    } 

}

+0

“近几个小时”?那是什么意思?不是一对夫妇,就这样,50分钟? –

+2

使用'std :: string'并调用'find_last_of()'会更好? – billz

+1

你为什么不调试你的程序?这真的很有帮助。 – dare

回答

2

'hlhh'是不是C++字符串和字符向量只能push_back单个字符有:

myArr.push_back('l'); 
myArr.push_back('l'); 
myArr.push_back('l'); 
myArr.push_back('h'); 
myArr.push_back('l'); 
myArr.push_back('h'); 
myArr.push_back('h'); 

而作为一个更好的做法,getIndex函数应成为:

int getIndex(vector<char> &myArr, char t); 

而不是

int getIndex(vector<char> myArr, char t); 

因为passing by value将生成新的vector<char>对象并复制输入对象的所有元素,从而产生性能开销。

3

你想std::string::rfind

std::string s = "hlhhhlh"; 

std::cout << "The last 'h' in '" << s << "' is at position " 
      << s.rfind('h') << std::endl; 

(如果该字符不字符串中出现,则返回s.npos

0

您要添加此: 'hlhh'多字节字符

myArr.push_back('hlhh'); 

他们需要单独添加,即

myArr.push_back('h'); 
myArr.push_back('l'); 
myArr.push_back('h'); 
myArr.push_back('h'); 
0

您可以使用String和rfind()来查找“Kerrek SB”建议的字符串中最后一次出现的字符。 如果你想使用字符串矢量然后下面的代码示例会帮助你,

#include<iostream> 
    #include<vector> 
    #include<string> 
    using namespace std; 


    int main() 
    { 
    vector<string> arr(0); 
    arr.push_back(string("h")); 
    arr.push_back(string("l")); 
    arr.push_back(string("h")); 
    arr.push_back(string("l")); 
    arr.push_back(string("h")); 
    arr.push_back(string("h")); 
    arr.push_back(string("l")); 
    arr.push_back(string("h")); 
    arr.push_back(string("l")); 
    arr.push_back(string("h")); 
    arr.push_back(string("l")); 
    for (int i=arr.size()-1; i >=0; i--) 
     if (arr[i] == string("h")) { 
      cout<<"\n H is present at"<< i; 
      break; 
     } 
    return 0; 
    } 
相关问题