Strings in C++ can be handled using two primary approaches:
1️⃣ C-Style Strings
- These are character arrays ending with a null character
(\0).
Example:
char str[] = "Hello";
- Common operations:
strlen(str): Get the length of the string (from<cstring>).strcpy(dest, src): Copy one string to another.strcmp(str1, str2): Compare two strings.
2️⃣ std::string (Preferred in Modern C++)
- Provided by the
<string>library. - Easier to use and safer than C-style strings.
Example:
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello, World!";
std::cout << greeting << std::endl;
return 0;
}
Features:
- Dynamic size management.
- Member functions like
.length(),.substr(),.find(),.append(), etc. - Operator overloading (e.g.,
+for concatenation).
