strings in cpp
strings in cpp
Introduction
Strings in C++ are used to store and manipulate sequences of characters. C++ provides two main ways to work with strings:
C-style strings (character arrays)
std::string
class (C++ strings)
Using std::string
is the preferred and safer method in modern C++.
C-style strings are arrays of characters terminated by a null character ('\0'
).
#include <iostream>
using namespace std;
int main() {
char name[20] = "Alice";
cout << "Name: " << name << endl;
return 0;
}
Output:
Name: Alice
Limitations:
Fixed size
Manual memory handling
Less secure compared to std::string
std::string
Class)The std::string
class (in <string>
header) is part of the C++ Standard Library and makes working with strings much easier.
Key Features:
Dynamic size (auto resizes)
Rich set of built-in functions
Safer and more convenient than C-style strings
std::string
#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "Alice";
cout << "Name: " << name << endl;
name += " Johnson"; // string concatenation
cout << "Full Name: " << name << endl;
cout << "Length: " << name.length() << endl;
return 0;
}
Output:
Name: Alice
Full Name: Alice Johnson
Length: 13
Function | Description |
---|---|
length() / size() | Returns number of characters |
append(str) | Appends a string |
substr(pos, len) | Returns substring |
find(str) | Finds the first occurrence |
replace(pos, len, str) | Replaces part of string |
c_str() | Returns C-style string |
#include <iostream>
#include <string>
using namespace std;
int main() {
string text = "Hello World";
cout << "Length: " << text.size() << endl;
cout << "Substring: " << text.substr(0, 5) << endl;
cout << "Find 'World': " << text.find("World") << endl;
text.replace(6, 5, "C++");
cout << "After replace: " << text << endl;
return 0;
}
Output:
Length: 11
Substring: Hello
Find 'World': 6
After replace: Hello C++
Strings are essential for handling textual data in C++. While C-style strings are older and less safe, std::string
provides powerful and flexible ways to work with strings.