如何检查字符串中存储"t"?
How do I check for stored " " in a string?
有人可以向我解释如何正确搜索存储在字符串类中的"制表符"字符吗?
例如:
文本.txt内容:
std::cout << "Hello"; // contains one tab space
用户在提示时输入:./a.out <文本.txt>文本.txt>
主.cpp:
string arrey;
getline(cin, arrey);
int i = 0;
while( i != 10){
if(arrey[i] == "t") // error here
{
std::cout << "I found a tab!!!!"
}
i++;
}
由于文本文件中只有一个制表符空间,我假设它存储在索引 [0] 中,但问题是我似乎无法进行比较,而且我不知道任何其他搜索方式。有人可以帮助解释替代方案吗?
Error: ISO C++ forbids comparison between pointer and integer
首先,什么是i
?其次,当你使用std::string
对象的数组索引时,你会得到一个字符(即char
)而不是一个字符串。
char
将转换为int
,然后编译器尝试将该int
与指向字符串文本的指针进行比较,并且您无法将纯整数与指针进行比较。
但是,您可以将一个字符与另一个字符进行比较,例如
arrey[i] == 't'
std::string::find()
可能会有所帮助。
试试这个:
...
if(arrey.find('t') != string::npos)
{
std::cout << "I found a tab!!!!";
}
有关std::string::find
的更多信息,请点击此处。
为什么不使用C++库提供的内容?你可以这样做:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string arrey;
getline(cin, arrey);
if (arrey.find("t") != std::string::npos) {
std::cout << "found a tab!" << 'n';
}
return 0;
}
代码基于此答案。这是 std::find 的参考。
关于您的编辑,如何确定输入将是 10 个位置?这可能太少或太大!如果它小于输入的实际大小,您将不会查看字符串的所有字符,如果它太大,您将溢出!
您可以使用 .size()
,它表示字符串的大小并使用如下所示的 for 循环:
#include <iostream>
#include <string>
using namespace std;
int main() {
string arrey;
getline(cin, arrey);
for(unsigned int i = 0; i < arrey.size(); ++i) {
if (arrey[i] == 't') {
std::cout << "I found a tab!!!!";
}
}
return 0;
}
相关文章:
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 在向量 C++14(无限制联合)的结构内的联合中创建和存储字符串
- 如何存储字符串列表
- 在向量中存储字符串存在 SEG 错误
- 指针存储字符串?
- 逐个字母存储字符串并打印
- 将字符数组转换为字符串并存储字符串?
- 当分配动态内存以存储字符串副本时,程序会中断
- 在C/C++中存储字符串、数组和指针,哪种方法更有效
- 我们如何以 7 位格式存储字符串
- C 存储字符串输入为CString
- TVItem lparam存储字符串
- C++以相反的顺序存储字符串
- 如果存储字符串的char数组小于字符串,则C++实际存储字符串
- 为什么我的 SetBookTitle 不存储字符串
- 如何在 C 中有效地存储字符串的映射
- 如何使用好友运算符存储字符串
- 如何在 C++ 中存储字符串和整数串联的变量
- 如何在 c++ 中存储字符串数组
- 存储字符串