In C++, a string is an object that represents a sequence of characters. Historically, C used "Character Arrays" (C-style strings), but modern C++ uses the <string> class, which is much safer and easier to use.
1. C-style Strings vs. C++ Strings
C-style: An array of characters ending with a null character
\0.Example:
char name[] = "Alex";(Actually stored as['A', 'l', 'e', 'x', '\0']).
C++ String Class: A dynamic object that grows as needed and has built-in functions.
Example:
string name = "Alex";
2. Useful String Functions
The <string> library gives you "superpowers" to manipulate text:
.length()or.size(): Returns the number of characters..append()or+: Joins two strings together (Concatenation).[index]: Accesses a specific character (just like an array)..empty(): Checks if the string has no text.
Code Example: Text Processing
This program takes a username, cleans it up, and checks its properties.
#include <iostream>
#include <string> // Must include this!
using namespace std;
int main() {
string firstName = "Master";
string lastName = "Coder";
// 1. Concatenation (Joining)
string fullName = firstName + " " + lastName;
cout << "Full Name: " << fullName << endl;
// 2. Getting Length
cout << "Length of name: " << fullName.length() << " characters." << endl;
// 3. Accessing and Modifying characters
cout << "First letter: " << fullName[0] << endl;
fullName[0] = 'm'; // Changing 'M' to 'm'
cout << "Modified Name: " << fullName << endl;
// 4. Taking a full line of input (with spaces)
string bio;
cout << "Enter a short bio: ";
getline(cin >> ws, bio); // ws skips leading whitespace
cout << "Your bio is: " << bio << endl;
// 5. Comparison
if (firstName == "Master") {
cout << "Greeting, Master!" << endl;
}
return 0;
}