如何在c++中对字符串中的每个字符进行for循环?
当前回答
for (int x = 0; x < yourString.size();x++){
if (yourString[x] == 'a'){
//Do Something
}
if (yourString[x] == 'b'){
//Do Something
}
if (yourString[x] == 'c'){
//Do Something
}
//...........
}
String基本上是一个字符数组,因此您可以指定索引来获取字符。如果您不知道索引,那么您可以像上面的代码一样对其进行循环,但是当您进行比较时,请确保使用单引号(它指定一个字符)。
除此之外,上面的代码是自解释的。
其他回答
Looping through the characters of a std::string, using a range-based for loop (it's from C++11, already supported in recent releases of GCC, clang, and the VC11 beta): std::string str = ???; for(char& c : str) { do_things_with(c); } Looping through the characters of a std::string with iterators: std::string str = ???; for(std::string::iterator it = str.begin(); it != str.end(); ++it) { do_things_with(*it); } Looping through the characters of a std::string with an old-fashioned for-loop: std::string str = ???; for(std::string::size_type i = 0; i < str.size(); ++i) { do_things_with(str[i]); } Looping through the characters of a null-terminated character array: char* str = ???; for(char* it = str; *it; ++it) { do_things_with(*it); }
const char* str = "abcde";
int len = strlen(str);
for (int i = 0; i < len; i++)
{
char chr = str[i];
//do something....
}
这是另一种方法,使用标准算法。
#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;
});
}
在现代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)。
for (int x = 0; x < yourString.size();x++){
if (yourString[x] == 'a'){
//Do Something
}
if (yourString[x] == 'b'){
//Do Something
}
if (yourString[x] == 'c'){
//Do Something
}
//...........
}
String基本上是一个字符数组,因此您可以指定索引来获取字符。如果您不知道索引,那么您可以像上面的代码一样对其进行循环,但是当您进行比较时,请确保使用单引号(它指定一个字符)。
除此之外,上面的代码是自解释的。
推荐文章
- 如何构建和使用谷歌TensorFlow c++ api
- 在Bash中模拟do-while循环
- 加快R中的循环操作
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?
- 在STL地图中,使用map::insert比[]更好吗?
- C++ Linux的想法?
- 如何为Fedora安装g++ ?
- Std::cin输入空格?
- c++标准是否要求iostreams的性能很差,或者我只是在处理一个糟糕的实现?
- gcc在哪里查找C和c++头文件?
- 为什么我们需要require require ?
- 如何计数列表中唯一值的出现
- 解析c++中的命令行参数?
- 我如何在c++中创建一个随机的字母数字字符串?