如果我有很多具有相似前缀的字符串,是否有理由从该前缀创建一个子字符串?

If I have lots of strings with a similar prefix, is there a reason to create a substring out of that prefix?

本文关键字:字符串 前缀 创建 一个 是否 相似 如果 有理由      更新时间:2023-10-16

我不确定如何表述这个问题。 我认为用一个例子更容易展示。

假设我的代码中有以下字符串:
std::string str1 = "Wild_Dog";
std::string str2 = "Wild_Cat";std::string str3 = "Wild_Human";

std::string str4 = "Wild_Goblin";
std::string str5 = "Wild_Dragon";

除了编码风格之外,还有什么理由来编写这样的代码吗?


std::string prefix = "Wild_";std::string str1 = prefix + "Dog";std::string str2 = prefix + "Cat";

std::string str3 = prefix + "Human";
std::string str4 = prefix + "Goblin";std::string str5 = prefix + "Dragon";

(注意:没有其他变量代替wild_***,所以它将永远是相同的前缀(

我想,我有点过度设计了:https://godbolt.org/z/x4wf5r。这应该具有最佳性能,并且前缀仅指定一次。