c++字符串回文数使用vector
时间: 2023-10-23 17:28:31 浏览: 38
以下是使用vector实现字符串回文数的示例代码:
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isPalindrome(string s) {
vector<char> v;
for (char c : s) {
if (isalnum(c)) {
v.push_back(tolower(c));
}
}
for (int i = 0, j = v.size() - 1; i < j; i++, j--) {
if (v[i] != v[j]) {
return false;
}
}
return true;
}
int main() {
string s = "A man, a plan, a canal: Panama";
cout << isPalindrome(s) << endl; // 输出 1
return 0;
}
```
此代码首先将字符串中的所有字母和数字转换为小写,并将它们存储在vector中。然后,使用两个指针从两端同时向中间遍历vector,判断其是否为回文数。如果遇到不相等的字符,则返回false,否则返回true。
相关问题
C++保存中文字符串到vector中
可以使用 C++ STL 的 vector 来存储 C 的中文字符串。
示例代码:
```C++
#include <vector>
#include <string>
int main() {
char str[] = "这是一个中文字符串";
std::vector<char> vec(str, str + sizeof(str));
return 0;
}
```
或者使用 string :
```C++
#include <vector>
#include <string>
int main() {
std::string str = "这是一个中文字符串";
std::vector<char> vec(str.begin(), str.end());
return 0;
}
```
如果你想要用 vector<string> 存储多个字符串,可以这样:
```C++
#include <vector>
#include <string>
int main() {
std::vector<std::string> vec;
vec.push_back("这是第一个字符串");
vec.push_back("这是第二个字符串");
vec.push_back("这是第三个字符串");
return 0;
}
```
用 C++实现使用 vector 求指定字符串
的出现次数该怎么做?
这个问题涉及到字符串查找和计数,可以使用C语言的标准库函数strstr和strchr来查找子串,再使用一个计数器变量记录出现次数即可。具体实现方法如下:
1. 定义一个计数器变量count,初始值为0。
2. 使用strchr函数查找指定字符串中第一个出现的字符,找到后用strstr函数判断是否是该字符串,若是则count加1。
3. 循环执行第2步,直到整个字符串被扫描完毕。
4. 输出count即为指定字符串出现的次数。
以下是具体的C语言代码实现:
```
#include <stdio.h>
#include <string.h>
int main()
{
char str[100] = "hello world, hello world!";
char substr[10] = "hello";
int count = 0;
char *p = str;
while(p = strchr(p, substr[0])) // 如果找到了第一个字符
{
if(strstr(p, substr) == p) // 如果匹配成功
{
count++;
}
p++; // 继续向后查找
}
printf("The number of substrings in the string is %d", count);
return 0;
}
```