Lesson 3 of 19
String Operations
Strings in C++
C++ std::string is a major improvement over C's null-terminated char* arrays. It manages memory automatically and comes with many built-in methods.
Creating Strings
#include <string>
using namespace std;
string name = "Alice";
string empty = "";
string repeated(5, 'x'); // "xxxxx"
Concatenation
Use + to combine strings:
string first = "Hello";
string second = "World";
string combined = first + ", " + second + "!";
// "Hello, World!"
Use += to append:
string s = "foo";
s += "bar"; // "foobar"
Length
string s = "hello";
cout << s.length() << endl; // 5
cout << s.size() << endl; // also 5
Substrings
substr(pos, length) extracts a portion of the string:
string s = "Hello, World!";
cout << s.substr(0, 5) << endl; // Hello
cout << s.substr(7, 5) << endl; // World
Finding Substrings
find returns the index of the first match, or string::npos if not found:
string s = "Hello, World!";
int pos = s.find("World"); // 7
int pos2 = s.find("xyz"); // string::npos
Comparing Strings
Use == and != directly:
string a = "hello";
string b = "hello";
if (a == b) cout << "equal" << endl;
Your Task
Build a sentence and then:
- Print the combined string
- Print its length
- Print the first 5 characters (using substr)
JSCPP loading...
Loading...
Click "Run" to execute your code.