C++ 逐个字符遍历字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14668326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:34:05  来源:igfitidea点击:

Iterate through string char by char

c++

提问by user1988385

I try to iterate through a string char by char. I tried something like this:

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

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

So this function call print("hello"); should return:

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

for(unsigned int i = 0; i<infix.length(); i++) {
    char c = infix[i]; //this is your character
}

I try using my code, but it doesn't work at all. btw the parameter is a reference not a pointer. Thank you

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

采纳答案by Dhaivat Pandya

void print(const std::string& infix)
{
    for(auto c : infix)
        std::cout << c << std::endl;
}

That's how I've done it. Not sure if that's too "idiomatic".

我就是这样做的。不知道这是否太“惯用”了。

回答by Mark Tolonen

Your code needs a pointer, not a reference, but if using a C++11 compiler, all you need is:

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

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

回答by 0x499602D2

If you're using std::string, there really isn't a reason to do this. You can use iterators:

如果您正在使用std::string,真的没有理由这样做。您可以使用迭代器:

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

As for your original code you should have been using char*instead of charand you didn't need the reference.

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

回答by billz

std::string::c_str()returns const char*, you can't use char&to hold it. Also exp is pointer already, you don't need reference:

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

Better use iterator though:

最好使用迭代器:

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

To fix your original code, try:

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

##代码##