C++:查找字符串中最后一个出现的字符
C++: Finding the last occurence of a char in a string
我已经为此工作了将近几个小时。我相信我的解决方案在逻辑上是正确的,但我没有得到所需的输出。例如,假设我想找到字符"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;
}
相关文章:
- 使用连续分隔符和空最后一个字符进行拆分
- CPP:如何获取字符的最后一个索引
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 比较最后一个字符,不区分大小写(带谓词?
- 在弦乐器中删除最后一个字符
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- 在C 字符串中,为什么在最后一个字符之后,通过索引和()访问索引时行为是不同的
- 如何查看复杂度为 O(1) 的字符串流对象中的最后一个字符
- 最后一个字符行编辑
- 如何在C 中获得字符串的最后一个字符
- 从字符串中删除字符的第一个和最后一个实例
- 删除文件 C++ 中字符串中最后一个出现的字符
- 如何在C++中删除 UTF-8 字符串的最后一个字符
- 如何将文本(诗歌)拆分为行(字符串/字符[])并查找每个行的最后一个单词
- 如何获取输入文件的行的第二个和最后一个字符,并在C++中组成数组
- 输出流中的第一个字符将替换为该流中被删除的最后一个字符.为什么会这样
- 正在将最后一个字符发送到std::cout
- 获取字符串流中的最后一个字符,而不复制其整个缓冲区
- remove_if字符串中的最后一个字符
- 如何删除最后一个字符