c++如何获取一个字符在string中的数量
时间: 2024-02-25 13:58:04 浏览: 16
你可以使用 string 类的 count() 函数来获取一个字符在 string 中的数量。count() 函数接受一个字符作为参数,并返回该字符在字符串中出现的次数。以下是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "hello world!";
char c = 'l';
int count = std::count(s.begin(), s.end(), c);
cout << "The character '" << c << "' appears " << count << " times in the string." << endl;
return 0;
}
```
输出如下:
```
The character 'l' appears 3 times in the string.
```
另外需要注意的是,为了调用 count() 函数,你需要在代码中包含 `<algorithm>` 头文件。
相关问题
如何获取一个字符在string中的数量
你可以使用 string 类的 count() 函数来获取一个字符在 string 中的数量。count() 函数接受一个字符作为参数,并返回该字符在字符串中出现的次数。以下是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "hello world!";
char c = 'l';
int count = s.count(c);
cout << "The character '" << c << "' appears " << count << " times in the string." << endl;
return 0;
}
```
输出如下:
```
The character 'l' appears 3 times in the string.
```
C++获取string的最后一个字符
可以通过 string 类的成员函数 `back()` 获取 string 的最后一个字符。例如:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
char last = str.back();
std::cout << "The last character is " << last << std::endl;
return 0;
}
```
输出结果:
```
The last character is !
```