C++ Strings Introduction
What are Strings?
In C++, strings are objects from the Standard Library (std::string
) that represent sequences of characters.
Unlike C-style character arrays, std::string
handles memory management automatically and provides many convenient functions for working with text, such as concatenation, searching, and substring extraction.
Strings are widely used to store and manipulate text like names, addresses, and messages.
String Declaration
To use std::string
, include the <string>
header (and <iostream>
when printing) and create string objects as shown below:
Example
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}
Output
Hello
String Initialization
Strings can be initialized in several different ways:
Example
#include <iostream>
#include <string>
int main() {
std::string s1; // Empty string
std::string s2 = "Hello"; // Initialized with literal
std::string s3("World"); // Constructor syntax
std::string s4(5, 'a'); // "aaaaa" - 5 copies of 'a'
std::cout << s2 << ' ' << s3 << ' ' << s4;
return 0;
}
Output
Hello World aaaaa