C++:查找字符串中最后一个出现的字符

C++: Finding the last occurence of a char in a string

本文关键字:字符 最后一个 查找 字符串 C++      更新时间:2023-10-16

我已经为此工作了将近几个小时。我相信我的解决方案在逻辑上是正确的,但我没有得到所需的输出。例如,假设我想找到字符"h"最后一次出现在这个字符串中的时间:"hlhhhlh"(如果从0开始,则为6)。

我的程序可以编译,但不起作用。此代码只在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;
          }
      }
  }

}

您想要std::string::rfind:

std::string s = "hlhhhlh";
std::cout << "The last 'h' in '" << s << "' is at position "
          << s.rfind('h') << std::endl; // output here is: The last 'h' in hlhhhlh is at position 6

(如果字符串中没有出现字符,则返回s.npos。)

'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>对象并复制输入对象的所有元素,从而产生性能开销。

您添加的是:"hlhh"一个多字节字符

myArr.push_back('hlhh');

它们需要单独添加,即

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

您可以使用String和rfind()来查找字符串中最后一个出现的字符,如"Kerrek SB"所建议的。如果您想将字符串与Vector一起使用,那么下面的示例代码将对您有所帮助,

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