字符串炭迭代仪
String Char Iterator
刚刚返回到C 中的编程。我遇到的错误:
请求成员开始发送的启动是非班级类型char [30]
send的会员端的请求是非班级类型char [30]
char sent[] = "need to break this shiat down";
for(vector<string>::iterator it=sent.begin(); it!=sent.end(); ++it){
if(*it == " ")
cout << "n";
else
cout << *it << endl;
}
我应该更改字符串或定义向量的字符串还是不同?
在其他答案中指出,您正在迭代错误的类型。您应该将sent
定义为std::string
类型,并使用std::string::begin()
和std::string::end()
进行迭代,或者,如果您有C 11支持,则可以轻松地在固定尺寸的数组上迭代一些选项。您可以使用std::begin
和STD :: End`:
char sent[] = "need to break this shiat down";
for(char* it = std::begin(sent); it != std::end(sent); ++it){
if(*it == ' ')
std::cout << "n";
else
std::cout << *it << "n";
}
或者您可以使用基于范围的循环:
char sent[] = "need to break this shiat down";
for (const auto& c : sent)
{
std::cout << c << "n";
}
您也可以使用流式扔掉空格并扔进新线。
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
stringstream ss("need to break this shiat down.", ios_base::in);
string s;
while (ss >> s)
cout << s << endl;
return EXIT_SUCCESS;
}
结果:
需要
破裂
这个
shiat
下来。
char sent[]
不是 std::string
,而是字符串字面 - 但是在这种情况下,您可以迭代它:
int main() {
char sent[] = "need to break this shiat down";
for(auto it = std::begin(sent); it!=std::end(sent) - 1; ++it){
if(*it == ' ')
cout << "n";
else
cout << *it << endl;
}
}
请注意,我将" "
更改为 ' '
-并跳过了最后一个null终止char ' '
...
实时示例:http://liveworkspace.org/code/55f826dfcf1903329c0f6f6f4e40682a12
对于C 03您可以使用以下方法:
int main() {
char sent[] = "need to break this shiat down";
for(char* it = sent; it!=sent+sizeof(sent) - 1; ++it){
if(*it == ' ')
cout << "n";
else
cout << *it << endl;
}
}
如果这是当时不知道的字符串字符串 - 使用strlen而不是sizeof ...
您的变量 sent
不是类型vector<string>
,而是char[]
。
但是,您的循环尝试在字符串的向量中尝试迭代。
对于平原阵列,使用C迭代:
int len = strlen(sent);
for (int i = 0; i < len; i++)
使用string
代替char[]
string sent = "need to break this shiat down";
for(string::iterator it=sent.begin(); it!=sent.end(); ++it){
if(*it == ' ')
cout << "n";
else
cout << *it << endl;
}
char[]
没有开始和结束方法。
相关文章:
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 迭代字符串集时没有可行的转换
- C++类字符串类型的迭代器
- 使用迭代器 C++ 删除矢量中的重叠字符串
- std::move(key) 同时迭代unordered_map<字符串,字符串>?
- 对于C字符串,是否有一个标准的C++迭代器
- 在for循环的某些迭代中,字符串的长度为0,而在其他迭代中则不为0
- Map中的(字符串的)向量迭代器
- 使用迭代从链表向后打印字符串
- std::string::find 为取消引用的迭代器和等效字符串文本返回不同的值
- 字符串迭代器永远不会达到 std::string::end()
- 如何在不迭代的情况下从string_view向量创建字符串向量?
- 字符串::是否替换了迭代器和引用?
- 如何迭代字符串向量的向量?(C )
- 迭代字符串 c++ 的错误
- 错误:具有索引或迭代字符串的"<"标记之前的预期初始值设定项
- 如何迭代C++字符串向量
- 当迭代字符串时,Stringstream不起作用
- 如何在C和C++中迭代字符串数组