C++ provides the std::string class (from <string>) for safer and more flexible string handling compared to C-style strings (char[]).
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "Hello";
string s2("World");
cout << s1 + " " + s2 << endl; // Hello World
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "Smarty";
name += " is learning C++ strings!";
cout << "Message: " << name << endl;
cout << "Length: " << name.length() << endl;
cout << "Characters: ";
for (char c : name) {
cout << c << " ";
}
cout << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string text = "I love coding in C++.";
size_t pos = text.find("coding");
if (pos != string::npos) {
text.replace(pos, 6, "building");
}
string lang = text.substr(text.find("C++"), 3); // "C++"
cout << "Updated: " << text << endl;
cout << "Language: " << lang << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Code at scale";
s.insert(5, "like a pro "); // after 'Code '
s.erase(0, 5); // remove "Code "
cout << s << endl;
string a = "abc", b = "xyz";
if (a < b) cout << "abc comes before xyz\\n";
return 0;
}