> For the complete documentation index, see [llms.txt](https://42-guide.gitbook.io/42-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://42-guide.gitbook.io/42-guide/all-about-c++/string-manipulation.md).

# String Manipulation

**Key `std::string` Methods**

* **`find()`**: Locate a substring.
* **`substr()`**: Extract a substring.
* **`erase()`**: Remove characters.
* **`insert()`**: Add characters.
* **`append()`/`+=`**: Concatenate strings.
* transgorm(): case conversion

#### **Example: Replace Substring Manually**

```cpp
std::string text = "I like apples.";
std::string oldStr = "apples";
std::string newStr = "oranges";

size_t pos = text.find(oldStr);

// Check if substring exists
if (pos != std::string::npos) {
    text.erase(pos, oldStr.length());  // Remove old substring
    text.insert(pos, newStr);          // Insert new substring
}

std::cout << text; // "I like oranges."
```

#### **Common Operations**

**Trim Whitespace**

```cpp
std::string str = "   Hello World!   ";
size_t start = str.find_first_not_of(" \t");
size_t end = str.find_last_not_of(" \t");

if (start != std::string::npos) {
    str = str.substr(start, end - start + 1);
}
```

**Case Conversion with `std::transform`**

**Goal**: Convert a string to uppercase or lowercase.\
**Code**:

```cpp
#include <algorithm> // Required for std::transform

std::string s = "Hello";
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
// Result: "HELLO"
```

**Explanation:**

* **`std::transform`**: A function that applies an operation (e.g., `toupper` or `tolower`) to every element in a range.
* **Parameters**:
  1. **`s.begin()`**: Start of the **input range** (first character of the string).
  2. **`s.end()`**: End of the **input range** (one position past the last character).
  3. **`s.begin()` (again)**: Start of the **output range** (where results are written).\
     \&#xNAN;*This is why `s.begin()` appears twice: we’re modifying the original string **in place***.
  4. **`::toupper`**: The operation to apply (convert to uppercase).

**Key Insight:**

* If you used `s.begin()` only once, the code wouldn’t know where to write the results. By specifying the **same start position for input and output**, you overwrite the original string with modified characters.

***

#### **3. Replace All Occurrences of a Character**

**Goal**: Replace all instances of `a` with `o` in "banana".\
**Code**:

```cpp
std::string fruit = "banana";
for (char &c : fruit) { // Loop by reference
  if (c == 'a') c = 'o';
}
// Result: "bonono"
```

**Explanation:**

* **`for (char &c : fruit)`**: Loop through each character in `fruit` **by reference** (`&`).
  * Using `&` allows modifying the original string. Without it, changes would apply to a copy, not the original.
* **`if (c == 'a') c = 'o'`**: Check if the character is `a`, then replace it with `o`.

***

#### **4. Erase-Remove Idiom (Delete All `_` Characters)**

**Goal**: Remove all underscores from a string.\
**Code**:

```cpp
#include <algorithm>
std::string s = "a_b_c_d";
s.erase(std::remove(s.begin(), s.end(), '_'), s.end());
// Result: "abcd"
```

**Explanation:**

* **`std::remove(s.begin(), s.end(), '_')`**:
  * Scans the string and shifts all non-`_` characters to the front.
  * Returns an iterator pointing to the **new logical end** of the string (after the last valid character).
* **`s.erase(new_end, s.end())`**:
  * Physically deletes the "leftover" characters from the new logical end to the actual end.

***

#### **5. String Splitting with `std::stringstream`**

**Goal**: Split "Apple Banana Cherry" into individual words.\
**Code**:

```cpp
#include <sstream>
std::string data = "Apple Banana Cherry";
std::stringstream ss(data); // Create a stream from the string
std::string token;

while (ss >> token) { // Extract tokens using spaces as delimiters
  std::cout << token << std::endl;
}
// Output: Apple\nBanana\nCherry
```

**Explanation:**

* **`std::stringstream`**: Converts a string into a stream, allowing input operations like `>>`.
* **`ss >> token`**: Extracts tokens separated by whitespace (spaces, tabs, newlines) automatically.
* The loop continues until `ss >> token` fails (no more tokens).

***

#### **6. String Reversal with `std::reverse`**

**Code**:

```
#include <algorithm>
std::string s = "hello";
std::reverse(s.begin(), s.end()); // Reverse the entire string
// Result: "olleh"
```

**Explanation:**

* **`std::reverse`**: Swaps characters symmetrically around the center of the range.
* **`s.begin()` and `s.end()`**: Define the range to reverse (the entire string).

***

#### **Why These Details Matter**

1. **In-Place vs. Copy**: Many operations (like `std::transform` or `std::reverse`) modify the original string when you use the same iterators for input and output.
2. **References in Loops**: Using `char &c` in loops allows direct modification of the string’s characters.
3. **Iterator Logic**: Functions like `std::remove` return a new "logical end" to the data, which you then use with `erase` to clean up.

***

#### **Key Takeaways**

* **`s.begin()` twice in `std::transform`**: The first defines the input start, the second defines where to write results.
* **Always use references** when modifying elements in a loop: `for (char &c : str)`.
* **Erase-Remove Idiom**: A two-step process to delete elements efficiently.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://42-guide.gitbook.io/42-guide/all-about-c++/string-manipulation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
