【问题标题】:Breaking up long Strings分解长字符串
【发布时间】:2014-10-21 22:02:46
【问题描述】:

干杯!我对这个编码社区完全陌生——但到目前为止我很享受它。如果我有一个字符串,并且 cout 是多行,我该如何分解这些行?

例如:

string famousVillains; 
famousVillains = 
"
Voldemort: skinny man with a fat backstory 
Ursula: fat lady with tentacles
The Joker: scary dude with make-up 
Cruella:  weird lady with dog obsession
Terminator: crazy guy in black."; 

当我发现这个时,我如何确保每个恶棍之间都有空格?我尝试使用

感谢您的帮助!

【问题讨论】:

  • 请尝试使用正确的格式,显示您尝试过的代码,并提供准确所需的输出,而不是手动操作。这会容易得多。
  • 当你说“空格”时,你的意思是换行吗?
  • C++ multiline string literal 的可能副本。但您可能真正想要的是结构化数据;所以class Character {private: string name; string description; public: /* methods here */}; 然后使用vector<Character> famousVillains;。这为您提供了更多处理字符、计算字符、添加和删除字符的选项......以及显示它们的不同方式。将所有数据存储为单个块状字符串更难处理。

标签: c++ string


【解决方案1】:

您可以创建std::map 或查找反派及其描述的表格。

struct Villain_Descriptions
{
  std::string name;
  std::string descripton;
};

Villain_Descriptions famous_villains[] =
{
  {"Voldemort", "skinny man with a fat backstory"}, 
  {"Ursula",    "fat lady with tentacles"},
  {"The Joker", "scary dude with make-up"},
  {"Cruella",   "weird lady with dog obsession"},
  {"Terminator", "crazy guy in black."},
};

查找表和std::map 结构允许您通过搜索恶棍的名字来获取他们的信息。
在您的方法中,您必须在字符串中搜索换行符或名称,然后提取子字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-08
    • 2015-04-08
    • 1970-01-01
    • 2015-08-09
    • 2019-12-23
    • 1970-01-01
    • 2016-02-05
    • 2021-11-13
    相关资源
    最近更新 更多