Skip to content

Commit 2574bad

Browse files
committed
🚀 String concatenation and use of stringstream
1 parent 0c629b8 commit 2574bad

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

CMakeLists.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,5 @@ set(CMAKE_CXX_STANDARD 11)
66
set(SOURCE_FILES main.cpp)
77
add_executable(LearningCpp ${SOURCE_FILES})
88
add_executable(Pythagoras src/pythagoras.cpp)
9-
add_executable(Greater src/greater.cpp)
9+
add_executable(Greater src/greater.cpp)
10+
add_executable(StringsConcat src/strings/concat.cpp)

src/strings/concat.cpp

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
 (0)