如何检查字符串中存储"t"?

How do I check for stored " " in a string?

本文关键字:存储 字符串 何检查 检查      更新时间:2023-10-16

有人可以向我解释如何正确搜索存储在字符串类中的"制表符"字符吗?

例如:

文本.txt内容:

        std::cout << "Hello"; // contains one tab space 

用户在提示时输入:./a.out <文本.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;
}