逐个字符遍历字符串字符

Iterate through string char by char

本文关键字:字符 字符串 遍历      更新时间:2023-10-16

我尝试逐个字符遍历字符串字符。我尝试了这样的事情:

void print(const string& infix)
{
char &exp = infix.c_str();
while(&exp!='')
{
         cout<< &exp++ << endl;
    }
}

所以这个函数调用print("hello");应该返回:

h
e
l
l
o

我尝试使用我的代码,但它根本不起作用。 顺便说一句,参数是引用而不是指针。谢谢

您的代码需要一个指针,而不是一个引用,但如果使用 C++11 编译器,您只需要:

void print(const std::string& infix)
{
    for(auto c : infix)
        std::cout << c << std::endl;
}
for(unsigned int i = 0; i<infix.length(); i++) {
    char c = infix[i]; //this is your character
}

我就是这样做的。不知道这是否太"惯用"。

如果您使用的是 std::string ,则确实没有理由这样做。您可以使用迭代器:

for (auto i = inflix.begin(); i != inflix.end(); ++i) std::cout << *i << 'n';

至于你的原始代码,你应该使用char*而不是char,你不需要参考。

std::string::c_str() 返回 const char* ,你不能用char&来保存它。exp 已经是指针了,你不需要参考:

不过最好使用迭代器:

void print(const string& infix)
{
  for (auto c = infix.begin(); c!=infix.end(); ++c)
  {
    std::cout << *c << "n";
  }
  std::cout << std::endl;
}

要修复原始代码,请尝试:

void print(const string& infix)
{
  const char *exp = infix.c_str();
  while(*exp!='')
  {
    cout << *exp << endl;
    exp++;
   }
 }