The std::string class is the standard way to represent and manipulate strings in modern C++. It is part of the <string> header and provides dynamic memory management along with numerous built-in functions for string operations.
- Stores and manages character sequences dynamically.
- Provides rich built-in functions for searching, modifying, and comparing strings.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "GeeksforGeeks";
cout << str;
return 0;
}
Output
GeeksforGeeks
Explanation: The program creates a std::string object and prints its contents.
Applications of the C++ String Class
The std::string class is widely used in many real-world programming tasks.
1. Extracting Part of a String
The substr() function can extract a portion of a string.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Programming";
cout << str.substr(3, 4);
return 0;
}
Output
gram
2. Checking Whether a String Contains Only Digits
#include <iostream>
#include <string>
using namespace std;
bool isDigits(string str) {
for (char ch : str)
if (!isdigit(ch))
return false;
return true;
}
int main() {
cout << isDigits("12345");
return 0;
}
Output
1
3. Replacing Spaces in a URL
#include <iostream>
#include <string>
using namespace std;
int main() {
string url = "google com in";
while (url.find(' ') != string::npos)
url.replace(url.find(' '), 1, "%20");
cout << url;
return 0;
}
Output
google%20com%20in
4. Searching for a Word
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Welcome to GeeksforGeeks";
cout << str.find("Geeks");
return 0;
}
Output
11
Advantages
The std::string class offers several benefits that make string handling easier and safer.
- Automatically manages memory and string resizing.
- Provides many built-in functions for string manipulation.
- Safer and easier to use than C-style character arrays.
Limitations
Despite its advantages, std::string has a few limitations.
- Uses slightly more memory than C-style strings.
- Some operations may involve memory allocation or copying.
- May not be ideal for highly memory-constrained applications.
Best Practices
Following these practices helps write cleaner and more efficient string-related code.
- Prefer std::string over C-style strings in modern C++.
- Use built-in functions instead of manual string manipulation.
- Pass large strings by const reference whenever possible.