|
| 1 | +#include <iostream> |
| 2 | +#include <sstream> |
| 3 | + |
| 4 | + |
| 5 | +/** |
| 6 | + * Append a char to a given text |
| 7 | + * @param text String which to append char |
| 8 | + * @param c Char to append to text |
| 9 | + * @return Text with char concatenated |
| 10 | + */ |
| 11 | +std::string append(std::string text, char c) { |
| 12 | + return text + c; |
| 13 | +} |
| 14 | + |
| 15 | +/** |
| 16 | + * Strings are immutable, so a new string is created |
| 17 | + * on each concatenation (Very expensive). Instead |
| 18 | + * is a best practice to use a string stream |
| 19 | + * |
| 20 | + * @return String created through string stream |
| 21 | + */ |
| 22 | +std::string constructLargeString() { |
| 23 | + std::stringstream stringBuilder; |
| 24 | + |
| 25 | + for (int i = 0; i < 100; ++i) { |
| 26 | + if (i % 10 == 0 && i > 0) { |
| 27 | + stringBuilder << std::endl; |
| 28 | + } |
| 29 | + |
| 30 | + stringBuilder << "HH"; |
| 31 | + } |
| 32 | + |
| 33 | + return stringBuilder.str(); |
| 34 | +} |
| 35 | + |
| 36 | +int main() { |
| 37 | + std::string text; |
| 38 | + |
| 39 | + // This is an empty string: |
| 40 | + std::cout << "Empty string:" << text << std::endl; |
| 41 | + |
| 42 | + // Is possible append chars to empty string |
| 43 | + text = append(text, '*'); |
| 44 | + std::cout << "Now string is: " << text << std::endl; |
| 45 | + |
| 46 | + // Concat with std::string |
| 47 | + text = text + " || Concatenated text"; |
| 48 | + std::cout << "Concatenated string is: " << text << std::endl; |
| 49 | + |
| 50 | + // Very large string assembled through string stream |
| 51 | + std::cout << "Large string is:" << std::endl; |
| 52 | + std::cout << constructLargeString() << std::endl; |
| 53 | + |
| 54 | + |
| 55 | + std::cout << std::endl << "Good bye!"; |
| 56 | +} |
0 commit comments