> ## Documentation Index
> Fetch the complete documentation index at: https://programming-for-career.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Strings in C++

> Learn about strings in C++ programming, including C-style strings (character arrays) and the C++ string class, with examples and common operations.

## Introduction

In C++, a **string** is a sequence of characters used to store and manipulate text. Strings are widely used in real-life applications, such as handling names, addresses, messages, and file operations.

C++ provides two ways to handle strings:

1. **C-style strings** (character arrays)
2. **C++ `string` class** (from `<string>` library)

Let's explore both with real-world examples.

## C-Style Strings (Character Arrays)

C-style strings are character arrays ending with a **null character (`\0`)**.

### Example:

```cpp theme={null}
#include <iostream>
using namespace std;

int main() {
    char name[] = "John"; // C-style string
    cout << "Hello, " << name << "!" << endl;
    return 0;
}
```

### Explanation:

* `char name[] = "John";` initializes a character array.
* The null character `\0` is automatically added at the end.

### Real-Life Analogy:

Think of a C-style string as a row of lockers where each locker stores a character:

| J | o | h | n | \0 |
| - | - | - | - | -- |

The `\0` tells C++ where the string ends.

#### Limitation of C-Style Strings:

* Fixed size (cannot grow dynamically).
* Difficult to manipulate (no built-in functions for concatenation, searching, etc.).

## C++ `string` Class (Modern Approach)

C++ provides the `string` class from the `<string>` library, which is more flexible and powerful.

### Example:

```cpp theme={null}
#include <iostream>
#include <string>
using namespace std;

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

### Explanation:

* `string name;` declares a string variable.
* `cin >> name;` takes input (but stops at space).
* `cout << name;` prints the string.

#### Real-Life Analogy:

Imagine `string` as a **dynamic notebook** where you can write, erase, and modify text freely.

### **Key Differences**

| Feature               | C-Style Strings (`char[]`)  | `std::string` (C++ Strings)               |
| --------------------- | --------------------------- | ----------------------------------------- |
| **Null-Termination**  | Yes (`\0` is required)      | No (`\0` is managed internally)           |
| **Memory Management** | Manual (fixed size)         | Dynamic (auto-resizes)                    |
| **Safer?**            | ❌ Prone to buffer overflows | ✅ Safer and more convenient               |
| **Functionality**     | Limited (needs `<cstring>`) | Rich methods (length, find, substr, etc.) |

**🔹 Best Practice:**\
Always prefer `std::string` over C-style strings **unless you have a specific reason to use character arrays** (e.g., low-level memory manipulation, embedded systems).

## Taking Full-Line Input (`getline`)

To handle multi-word input, use `getline()`.

### Example:

```cpp theme={null}
#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;
}
```

### Why `getline()`?

`cin` only takes a single word, but `getline(cin, variable);` reads the whole line, including spaces.

## String Operations

### Concatenation (Joining Strings)

```cpp theme={null}
#include <iostream>
#include <string>
using namespace std;

int main() {
    string firstName = "John";
    string lastName = "Doe";
    string fullName = firstName + " " + lastName;
    cout << "Full Name: " << fullName << endl;
    return 0;
}
```

### Explanation:

* `+` operator joins strings.
* `" "` adds a space between first and last names.

### Finding String Length

```cpp theme={null}
string str = "Hello";
cout << "Length: " << str.length() << endl; // Output: 5
```

### Accessing Characters

```cpp theme={null}
cout << str[0]; // First character (H)
```

### Modifying Strings

```cpp theme={null}
str[0] = 'h'; // Changes "Hello" to "hello"
```

## Common Errors and Solutions

| **Error**            | **Cause**                 | **Solution**                                   |
| -------------------- | ------------------------- | ---------------------------------------------- |
| `cin` skips input    | `getline()` follows `cin` | Use `cin.ignore()` before `getline()`          |
| String out of bounds | Accessing invalid index   | Ensure index is within `0` to `str.length()-1` |
| Concatenation error  | Using `+` with `char[]`   | Use `string` class instead of `char[]`         |

## Conclusion

* **C-style strings** are character arrays with `\0` termination.
* **C++ `string` class** is modern and easy to use.
* **`getline()`** handles multi-word input.
* String operations include concatenation, length, access, and modification.

In the next article, we'll explore **Mathematical Functions in C++** to perform numerical operations efficiently.
