如何在c++中对字符串中的每个字符进行for循环?
当前回答
可以使用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]);
}
}
其他回答
你可以通过使用字符串库中的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++中:
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;
});
}
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++字符串,很容易处理。
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++中创建一个随机的字母数字字符串?