C++ std::string Class
The std::string class in C++ is a part of the
1. Declaration and Initialization
To use std::string, include the
C++
Example: Declaration and initialization
#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "John";
string city("New York");
cout << name << " from " << city;
return 0;
}
2. Input and Output
std::string supports easy input and output using cin, getline, and cout.
C++
Example: Using getline()
#include <iostream>
#include <string>
using namespace std;
int main() {
string fullName;
cout << "Enter your full name: ";
getline(cin, fullName);
cout << "Hello, " << fullName;
return 0;
}
3. Common Member Functions
The std::string class provides many built-in member functions.
C++
Example: String operations
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
cout << "Length: " << str.length() << endl;
str.append(" World");
cout << "After append: " << str << endl;
cout << "Substring: " << str.substr(0, 5) << endl;
return 0;
}
4. String Operations
You can concatenate, compare, and access characters in std::string easily.
C++
Example: String comparison and access
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "Apple";
string b = "Banana";
if (a < b) {
cout << "Apple comes before Banana" << endl;
}
cout << "First character of a: " << a[0] << endl;
return 0;
}
5. Advantages of std::string
1. Automatic memory management. 2. No need for null terminator handling. 3. Built-in functions for string manipulation. 4. Safer than C-style strings.
Conclusion
The std::string class provides a modern, safe, and powerful way to work with text in C++. It is recommended over C-style strings for most applications.
Codecrown