C++ 如何将一个包含超过1个字符I';我在找什么?
我正在编写一个程序,它可以接收由空格分隔的多个名称,如C++ 如何将一个包含超过1个字符I';我在找什么?,c++,c++17,C++,C++17,我正在编写一个程序,它可以接收由空格分隔的多个名称,如“John Paul Andrew”,并将这些名称转换为std::map的键 它可以使用两个名称,但三个或更多名称将字符串分隔为: Andrew John John Paul 以下是我如何拆分字符串: for (int i = 0; i < names.size() - 1; i++) { std::string::size_type pos = names.find(" ", i);
“John Paul Andrew”
,并将这些名称转换为std::map的键
它可以使用两个名称,但三个或更多名称将字符串分隔为:
Andrew
John
John Paul
以下是我如何拆分字符串:
for (int i = 0; i < names.size() - 1; i++) {
std::string::size_type pos = names.find(" ", i);
std::cout << "Position of space: " << pos << std::endl; // For debugging
if (pos != std::string::npos) {
std::string name = names.substr(0, pos);
scoreboard[name] = 0;
} else {
std::string name = names.substr(names.rfind(" ") + 1);
scoreboard[name] = 0;
}
}
for(int i=0;i std::cout您有i
作为索引器,它可以帮助您找到正在处理的单词。因此,您不需要像我建议的那样使用old\u pos
,因为i
已经可以用于此目的
#include <iostream>
#include <string>
#include <map>
using std::cout;
using std::map;
using std::string;
static auto make_scoreboard(string names) -> map<string, int> {
auto scoreboard = map<string, int>{};
for (decltype(names.size()) i = 0; i < names.size() - 1; i++) {
auto pos = names.find(" ", i);
cout << "Position of space: " << pos << "\n"; // For debugging
if (pos != string::npos) {
auto name = names.substr(i, pos - i);
scoreboard[name] = 0;
i = pos;
} else {
string name = names.substr(names.rfind(" ") + 1);
scoreboard[name] = 0;
i = names.size();
}
}
return scoreboard;
}
int main() {
auto names = string{"John Paul Andrew"};
auto scoreboard = make_scoreboard(names);
for(auto&& s : scoreboard) {
cout << s.first << "\n";
}
}
#包括
#包括
#包括
使用std::cout;
使用std::map;
使用std::string;
静态自动生成记分板(字符串名称)->映射{
自动记分板=地图{};
对于(decltype(names.size())i=0;i名称的每个字符(最后一个字符除外!),使用当前循环位置作为查找()的起始位置。
空格字符。这不是您应该使用的逻辑
让我们按照逻辑,使用您的示例“John Paul Andrew”
作为要拆分的名称
- 在第1-5次循环迭代中,
i
是0..4
,名称。find(“,i)
每次返回4。然后调用名称。substr(0,4)
返回“John”
。因此,将0分配给记分牌[“John”]
5次
- 在第6-10次循环迭代中,
i
是5..9
,名称。find(“,i)
每次返回9。然后调用名称。substr(0,9)
返回“John Paul”
。因此,您将0分配给记分牌[“John Paul”]
5次
- 在第11-15次循环迭代中,
i
是10..14
,names.find(“,i)
每次返回std::string::npos
。然后调用names.rfind(“”)
,返回9,然后调用names.substr(9+1)
,返回“Andrew”
。因此您将0分配给记分牌[“Andrew”]
5次
现在看到问题了吗
至少,由于您一次只能循环使用名称
一个字符,因此不应使用名称。find()
,例如:
std::string::size\u type start=0;
对于(STD:SIZEX类型i=0;i < sid();+ /考虑<代码> No.Sub(0,POS);小心。我做了,但我不知道该用什么来替换它。您可以初始化<代码> OLDPOS=0;< /Cord>,然后使用<代码> No.SUB(OLDPOS,POS -OLDPOS)。
,然后存储old_pos=pos+1;
。我会试试。谢谢!好吧,我刚试过,结果仍然一样。谢谢!这非常有效!auto scoreboard=map{};
?decltype(names.size())
??真的吗?太多的汽车了…@armimontigny•我的一位前同事建议。使用std::istringstream
是更好的答案…+1std::istringstream
方法非常有效!谢谢!