如何在c++中对字符串中的每个字符进行for循环?
当前回答
在现代c++中:
std::string s("Hello world");
for (char & c : s)
{
std::cout << "One character: " << c << "\n";
c = '*';
}
在 C++98/03 中:
for (std::string::iterator it = s.begin(), end = s.end(); it != end; ++it)
{
std::cout << "One character: " << *it << "\n";
*it = '*';
}
对于只读迭代,在c++ 98中可以使用std::string::const_iterator,在c++ 11中可以使用For (char const & C:s)或仅For (char C:s)。
其他回答
可以使用size()方法获取字符串的长度,使用方括号操作符访问每个字符。
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin >> s;
int length = s.size();
for(int i = 0; i < length; i++)
{
process(s[i]);
}
}
const char* str = "abcde";
int len = strlen(str);
for (int i = 0; i < len; i++)
{
char chr = str[i];
//do something....
}
for循环可以这样实现:
string str("HELLO");
for (int i = 0; i < str.size(); i++){
cout << str[i];
}
这将逐字符打印字符串。Str [i]返回索引i处的字符。
如果是字符数组:
char str[6] = "hello";
for (int i = 0; str[i] != '\0'; i++){
cout << str[i];
}
基本上以上两个是c++支持的两种类型的字符串。 第二个称为c字符串,第一个称为std字符串或(c++字符串)。我建议使用c++字符串,很容易处理。
在现代c++中:
std::string s("Hello world");
for (char & c : s)
{
std::cout << "One character: " << c << "\n";
c = '*';
}
在 C++98/03 中:
for (std::string::iterator it = s.begin(), end = s.end(); it != end; ++it)
{
std::cout << "One character: " << *it << "\n";
*it = '*';
}
对于只读迭代,在c++ 98中可以使用std::string::const_iterator,在c++ 11中可以使用For (char const & C:s)或仅For (char C:s)。
我没有看到任何使用“c字符串”的基于范围的for循环的例子。
char cs[] = "This is a c string\u0031 \x32 3";
// range based for loop does not print '\n'
for (char& c : cs) {
printf("%c", c);
}
不是相关的,而是int数组的例子
int ia[] = {1,2,3,4,5,6};
for (int& i : ia) {
printf("%d", i);
}