Summary - Strings
- C++ course
- Beginner
- Lesson 35/116
- 5 min
Combine concatenation, substr and find to write a business card.
Summary - Strings
In this group you learned the core tools of std::string: concatenation with +, appending with append, counting characters with length/size, slicing with substr and searching with find.
Now you will combine them in a small business card app. First you will join the first and last name with a space, then take the initials from the resulting string with substr. Such combined tasks appear all the time in real projects.
Practice Business card - full name
The firstName and lastName variables are given. Build fullName as firstName + " " + lastName and print it with std::cout.
Starter code
#include <iostream>
#include <string>
int main() {
std::string firstName = "Alex";
std::string lastName = "Brown";
// Build fullName by concatenation here
return 0;
}Sample solution
#include <iostream>
#include <string>
int main() {
std::string firstName = "Alex";
std::string lastName = "Brown";
std::string fullName = firstName + " " + lastName;
std::cout << fullName << std::endl;
return 0;
}Expected output
Alex Brown
Practice Business card - initials
The s variable is set to "Merhaba". Take the first three characters with s.substr(0, 3) into the part variable and print it with std::cout. The output must be Mer.
Starter code
#include <iostream>
#include <string>
int main() {
std::string s = "Merhaba";
// Take the first three characters into part and print
return 0;
}Sample solution
#include <iostream>
#include <string>
int main() {
std::string s = "Merhaba";
std::string part = s.substr(0, 3);
std::cout << part << std::endl;
return 0;
}Expected output
Mer
Next step
Well done! You learned the five most common tools of std::string: + for concatenation, append to add at the end, length for the count, substr for slicing and find for searching.
In the next group you will make your program behave differently in different situations with conditional expressions. Building logic with if, else and switch is the foundation of real applications.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does std::string s = "Welcome"; s.find("co") return?
std::string s = "Welcome";
s.find("co")- 5
- -1
- 0
- 3 Correct answer
Explanation: "co" starts at index 3; find returns 3.
2 Write the substr call
std::string s = "Welcome";
std::string first3 = s____(0, 3);
std::string s = "Welcome";
std::string first3 = s.substr(0, 3);
Explanation: .substr(0, 3) returns the first three characters.