std::string Class in C++

 


In C++, the std::string class (part of the Standard Library) provides a powerful and flexible way to handle strings. It is included in the <string> header and replaces traditional C-style character arrays (char[]).


1️⃣ Declaring and Initializing a String

Example: Creating Strings

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Hello";  // Direct initialization
    string str2("World");   // Constructor initialization
    string str3;            // Empty string
    str3 = "C++ Strings";   // Assignment

    cout << str1 << " " << str2 << " " << str3 << endl;
    return 0;
}

Output:

Hello World C++ Strings

2️⃣ Taking Input Using std::string

Using cin (Single Word Input)

#include <iostream>
#include <string>
using namespace std;

int main() {
    string name;
    cout << "Enter your name: ";
    cin >> name;  // Accepts only a single word
    cout << "Hello, " << name << "!" << endl;
    return 0;
}

📌 Note: cin stops reading at spaces. If you enter "John Doe", only "John" is stored.

Using getline() (Multiple Word Input)

#include <iostream>
#include <string>
using namespace std;

int main() {
    string fullName;
    cout << "Enter your full name: ";
    getline(cin, fullName);
    cout << "Hello, " << fullName << "!" << endl;
    return 0;
}

📌 Tip: If getline() is used after cin, use cin.ignore() to clear the newline character.


3️⃣ Common String Operations

🔹 String Concatenation (+ Operator)

string first = "Hello";
string second = "World";
string result = first + " " + second;  
cout << result << endl;  // Output: Hello World

🔹 Getting String Length (.length() or .size())

string text = "Programming";
cout << "Length: " << text.length() << endl; // Output: 11

🔹 Accessing Characters ([] or .at())

string word = "Code";
cout << word[0] << endl;      // Output: C
cout << word.at(1) << endl;   // Output: o

🔹 Modifying Strings

string text = "Hello";
text.append(" C++");  // Adds " C++" to the string
cout << text << endl;  // Output: Hello C++

🔹 Substring Extraction (substr())

string sentence = "Hello, World!";
string sub = sentence.substr(7, 5);  // Extracts "World"
cout << sub << endl;

🔹 Finding a Substring (find())

string sentence = "C++ programming is fun!";
size_t pos = sentence.find("programming");

if (pos != string::npos)
    cout << "Found at position: " << pos << endl;
else
    cout << "Not found" << endl;

🔹 Erasing a Part of the String (erase())

string str = "Hello World!";
str.erase(5, 6);  // Removes " World"
cout << str << endl; // Output: Hello

4️⃣ String Comparison

Using ==, <, > Operators

string str1 = "Apple";
string str2 = "Banana";

if (str1 == str2)
    cout << "Strings are equal";
else if (str1 < str2)
    cout << str1 << " comes before " << str2;
else
    cout << str2 << " comes before " << str1;

📌 Note: String comparisons are lexicographical (dictionary order).


5️⃣ Converting Between std::string and char[]

String to C-String (c_str())

string cppString = "Hello";
const char* cString = cppString.c_str();  // Convert to C-style string
cout << cString << endl;

C-String to std::string

char cstr[] = "Hello";
string cppString = cstr;  // Implicit conversion
cout << cppString << endl;

6️⃣ Checking if a String is Empty

string s = "";
if (s.empty())
    cout << "String is empty!";

Conclusion

The std::string class provides powerful and flexible ways to work with text in C++. It eliminates the need for manual memory management (like char[]) and offers easy-to-use functions.

Would you like an example of reversing a string using std::string? 🚀

Post a Comment

0 Comments