الطريقة المثلى لإنشاء سلسلة كبيرة تحتوي على عدة متغيرات؟
-
21-09-2019 - |
سؤال
أريد إنشاء سلسلة تحتوي على العديد من المتغيرات:
std::string name1 = "Frank";
std::string name2 = "Joe";
std::string name3 = "Nancy";
std::string name4 = "Sherlock";
std::string sentence;
sentence = name1 + " and " + name2 + " sat down with " + name3;
sentence += " to play cards, while " + name4 + " played the violin.";
هذا يجب أن ينتج جملة تقرأ
جلس فرانك وجو مع نانسي للعب الورق ، بينما لعب شيرلوك الكمان.
سؤالي هو: ما هي الطريقة المثلى لإنجاز هذا؟ أشعر بالقلق من أن استخدام عامل + مشغل مستمر غير فعال. هل هناك طريقة أفضل؟
المحلول
نعم، std::stringstream
, ، على سبيل المثال:
#include <sstream>
...
std::string name1 = "Frank";
std::string name2 = "Joe";
std::string name3 = "Nancy";
std::string name4 = "Sherlock";
std::ostringstream stream;
stream << name1 << " and " << name2 << " sat down with " << name3;
stream << " to play cards, while " << name4 << " played the violin.";
std::string sentence = stream.str();
نصائح أخرى
يمكنك استخدام Boost :: Format لهذا:
http://www.boost.org/doc/libs/1_41_0/libs/format/index.html
std::string result = boost::str(
boost::format("%s and %s sat down with %s, to play cards, while %s played the violin")
% name1 % name2 % name3 %name4
)
هذا مثال بسيط للغاية لما يمكن أن يفعله Boost :: Format ، إنه مكتبة قوية للغاية.
يمكنك استدعاء وظائف الأعضاء مثل operator+=
على المنشأة. لسوء الحظ ، لديها ارتباط خاطئ ، ولكن يمكننا إصلاح ذلك مع أقواس.
std::string sentence(((((((name1 + " and ")
+= name2) += " sat down with ")
+= name3) += " to play cards, while ")
+= name4) += " played the violin.");
إنه قبيح بعض الشيء ، لكنه لا ينطوي على أي منشآت غير ضرورية.
لا تنتمي إلى StackOverflow