Ugrás a tartalomhoz

Szerkesztő:LinguisticMystic/cpp/StringsText

A Wikiszótárból, a nyitott szótárból

std::string in C++

[szerkesztés]

🔷 What is std::string and Why Is It Needed?

[szerkesztés]

In C++, std::string is a standard class provided by the C++ Standard Library (<string>) for handling text. It wraps a sequence of characters and allows powerful, flexible manipulation through an intuitive interface—far simpler and safer than dealing with raw char arrays (C-style strings).



🆚 C-Style Strings vs std::string

[szerkesztés]

1. C-style string

[szerkesztés]
  • Represented by a char array terminated by a null character ('\0')

  • Example:

    char myString[] = "Hello, C-style strings!";
    std::cout << myString << std::endl;
    
  • ❗️C-style strings are low-level:

    • Difficult to manipulate
    • No bounds checking
    • Require manual memory management
    • Error-prone

2. std::string

[szerkesztés]
  • Defined as a class in the std namespace.

  • Encapsulates a dynamic array of characters with built-in methods.

  • Example:

    #include <iostream>
    #include <string>
    
    int main() {
        std::string myString = "Hello, World!";
        std::cout << myString << std::endl;
        return 0;
    }
    
  • ✅ Easier to:

    • Append
    • Insert
    • Erase
    • Replace
    • Compare
    • Convert



🧱 Initialization of std::string

[szerkesztés]
std::string str1;                    // Empty string
std::string str2 = "Hello, World!";  // From literal
std::string str3(str2);              // Copy constructor
std::string str4 = str3;             // Copy assignment

🧰 Common Operations

[szerkesztés]

✅ Append

[szerkesztés]
std::string greeting = "Hello";
greeting.append(", World!");
greeting += " Again!";
greeting.push_back('!');

✅ Insert / Erase

[szerkesztés]
std::string msg = "Hello, World!";
msg.insert(6, "beautiful ");  // "Hello, beautiful World!"
msg.erase(6, 10);             // "Hello, World!"

✅ Replace

[szerkesztés]
std::string greeting = "Hello, World!";
greeting.replace(7, 5, "there"); // "Hello, there!"

✅ Find & Substring

[szerkesztés]
std::string text = "Hello, World!";
int pos = text.find("World");        // 7
std::string sub = text.substr(7, 5); // "World"

✅ Compare

[szerkesztés]
std::string a = "apple", b = "banana";
if (a < b) std::cout << "apple comes first\n"; // Lexicographic comparison

🔁 Conversion

[szerkesztés]

Number to String

[szerkesztés]
int i = 123;
std::string s1 = std::to_string(i); // "123"
double d = 3.14;
std::string s2 = std::to_string(d); // "3.140000"

String to Number

[szerkesztés]
std::string s = "456";
int num = std::stoi(s); // 456
std::string dstr = "3.14";
double val = std::stod(dstr); // 3.14

⚠️ May throw std::invalid_argument or std::out_of_range.



📏 Size, Access, Empty Check

[szerkesztés]
std::string str = "Hello";
std::cout << str.length() << '\n';     // 5
std::cout << str.size() << '\n';       // 5 (equivalent)
std::cout << str[1] << '\n';           // 'e'
std::cout << str.at(1) << '\n';        // 'e' (throws if index is out-of-range)
std::cout << std::boolalpha << str.empty(); // false

🧾 Summary Table

[szerkesztés]
Operation Method or Syntax Example
Append +=, append(), push_back() "Hi" + " there"
Insert insert(pos, str) s.insert(3, "abc")
Erase erase(pos, len) s.erase(5, 2)
Replace replace(pos, len, str) s.replace(0, 4, "New")
Substring substr(pos, len) s.substr(1, 3)
Find find(str), rfind(str) s.find("abc")
Compare ==, <, etc. if (a < b)
Convert string → int stoi(s) int x = stoi("123");
Convert int → string to_string(x) std::to_string(123)
Check empty empty() if (s.empty())
Get length length(), size() s.length()
Character access [], at() s.at(3)



✅ Conclusion

[szerkesztés]

The std::string class is one of the most important utilities in C++:

  • It simplifies text processing.
  • Offers memory-safe, exception-safe features.
  • Replaces error-prone C-style strings.
  • Allows efficient and expressive code.

For real-world development, always prefer std::string unless you have a performance-critical or system-level reason to use char[].