如何在c++中对字符串中的每个字符进行for循环?
当前回答
你可以通过使用字符串库中的at函数来获取字符串中的每一个char,就像我这样做的
string words;
for (unsigned int i = 0; i < words.length(); i++)
{
if (words.at(i) == ' ')
{
spacecounter++; // to count all the spaces in a string
if (words.at(i + 1) == ' ')
{
i += 1;
}
这只是我的一段代码重点是你可以通过stringname。at(index)访问字符
其他回答
对于C-string (char[]),你应该这样做:
char mystring[] = "My String";
int size = strlen(mystring);
int i;
for(i = 0; i < size; i++) {
char c = mystring[i];
}
对于std::string,你可以使用str.size()来获取它的大小并像示例一样迭代,或者可以使用迭代器:
std::string mystring = "My String";
std::string::iterator it;
for(it = mystring.begin(); it != mystring.end(); it++) {
char c = *it;
}
在现代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)。
这是另一种方法,使用标准算法。
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string name = "some string";
std::for_each(name.begin(), name.end(), [] (char c) {
std::cout << c;
});
}
你可以通过使用字符串库中的at函数来获取字符串中的每一个char,就像我这样做的
string words;
for (unsigned int i = 0; i < words.length(); i++)
{
if (words.at(i) == ' ')
{
spacecounter++; // to count all the spaces in a string
if (words.at(i + 1) == ' ')
{
i += 1;
}
这只是我的一段代码重点是你可以通过stringname。at(index)访问字符
我没有看到任何使用“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);
}