> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/17.-useful-string-methods.md).

# 17. Useful String Methods

`std::string` comes with built-in methods for checking, changing, and cleaning up text. These are called with dot notation: `myString.methodName()`.

```cpp
#include <iostream>
#include <string>
```

***

### `.length()` — get the number of characters

Returns how many characters are in the string.

```cpp
#include <iostream>
#include <string>

int main() {
    std::string name;

    std::cout << "Enter your name: ";
    std::cin >> name;

    if (name.length() > 10) {
        std::cout << "That name is too long, max is 10 characters\n";
    }
    else {
        std::cout << "Welcome, " << name << '\n';
    }

    return 0;
}
```

This is a common pattern for validating input, checking that something isn't too short or too long before accepting it.

***

### `.empty()` — check if a string has anything in it

Returns `true` if the string has zero characters, `false` otherwise. Note it doesn't take an argument, and it returns a `bool`, not a number.

```cpp
#include <iostream>
#include <string>

int main() {
    std::string input;

    std::cout << "Enter something (or press Enter to skip): ";
    std::getline(std::cin, input);

    if (input.empty()) {
        std::cout << "You didn't type anything\n";
    }
    else {
        std::cout << "You typed: " << input << '\n';
    }

    return 0;
}
```

A quick way to tell `.empty()` apart from `.length() == 0`: they check the same thing, but `.empty()` reads more clearly and is slightly faster on some implementations, so it's the preferred style.

***

### `.clear()` — wipe a string back to empty

Removes every character, leaving the string at length 0.

```cpp
#include <iostream>
#include <string>

int main() {
    std::string message = "Hello there";

    std::cout << "Before: " << message << '\n';

    message.clear();

    std::cout << "After: " << message << '\n';
    std::cout << "Is empty now: " << message.empty() << '\n'; // 1 (true)

    return 0;
}
```

***

### `.append()` — add text to the end of a string

Sticks more characters onto the end of an existing string. Similar to using `+=`, but `.append()` is the explicit method form.

```cpp
#include <iostream>
#include <string>

int main() {
    std::string greeting = "Hello";

    greeting.append(", world!");

    std::cout << greeting << '\n'; // Hello, world!

    return 0;
}
```

Building a string piece by piece:

```cpp
#include <iostream>
#include <string>

int main() {
    std::string fullName;

    fullName.append("John");
    fullName.append(" ");
    fullName.append("Doe");

    std::cout << fullName << '\n'; // John Doe

    return 0;
}
```

***

### `.erase()` — remove part of a string

Deletes a chunk of characters, starting at one position and running for a given length: `str.erase(startIndex, numberOfCharacters)`.

```cpp
#include <iostream>
#include <string>

int main() {
    std::string phrase = "Hello, cruel world!";

    phrase.erase(7, 6); // start at index 7, remove 6 characters ("cruel ")

    std::cout << phrase << '\n'; // Hello, world!

    return 0;
}
```

Remember: string indexes start at 0, so `phrase[0]` is `H`, `phrase[7]` is `c`, and so on.

```cpp
#include <iostream>
#include <string>

int main() {
    std::string word = "programming";

    word.erase(0, 3); // removes "pro" from the start

    std::cout << word << '\n'; // gramming

    return 0;
}
```

***

### More cool examples

#### 1. Username validator using `.length()` and `.empty()` together

```cpp
#include <iostream>
#include <string>

int main() {
    std::string username;

    std::cout << "Enter a username (3-15 characters): ";
    std::cin >> username;

    if (username.empty()) {
        std::cout << "Username cannot be blank\n";
    }
    else if (username.length() < 3) {
        std::cout << "Too short\n";
    }
    else if (username.length() > 15) {
        std::cout << "Too long\n";
    }
    else {
        std::cout << "Username accepted: " << username << '\n';
    }

    return 0;
}
```

#### 2. A simple "reset" feature using `.clear()`

```cpp
#include <iostream>
#include <string>

int main() {
    std::string notes;
    char choice;

    std::cout << "Enter a note: ";
    std::getline(std::cin, notes);

    std::cout << "Clear the note? (y/n): ";
    std::cin >> choice;

    if (choice == 'y' || choice == 'Y') {
        notes.clear();
    }

    std::cout << "Current note: \"" << notes << "\"\n";

    return 0;
}
```

#### 3. Building a sentence with `.append()`

```cpp
#include <iostream>
#include <string>

int main() {
    std::string firstName, lastName;

    std::cout << "First name: ";
    std::cin >> firstName;

    std::cout << "Last name: ";
    std::cin >> lastName;

    std::string sentence = "Hello, my name is ";
    sentence.append(firstName);
    sentence.append(" ");
    sentence.append(lastName);
    sentence.append(".");

    std::cout << sentence << '\n';

    return 0;
}
```

#### 4. Removing a censored word with `.erase()`

```cpp
#include <iostream>
#include <string>

int main() {
    std::string text = "This product is absolutely terrible!";

    // remove "absolutely " starting at index 16, 11 characters long
    text.erase(16, 11);

    std::cout << text << '\n'; // This product is terrible!

    return 0;
}
```

#### 5. Combining all five methods in one flow

```cpp
#include <iostream>
#include <string>

int main() {
    std::string input;

    std::cout << "Enter some text: ";
    std::getline(std::cin, input);

    if (input.empty()) {
        std::cout << "Nothing entered\n";
        return 1;
    }

    std::cout << "Length: " << input.length() << '\n';

    input.append(" [reviewed]");
    std::cout << "After append: " << input << '\n';

    input.erase(0, 6); // remove the first 6 characters
    std::cout << "After erase: " << input << '\n';

    input.clear();
    std::cout << "Is empty after clear: " << input.empty() << '\n';

    return 0;
}
```

***

### Quick Recap

| Method                 | Does                                                                      | Returns                                                     |
| ---------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------- |
| `.length()`            | Counts characters                                                         | `int` (the count)                                           |
| `.empty()`             | Checks if the string has zero characters                                  | `bool`                                                      |
| `.clear()`             | Removes all characters                                                    | nothing (modifies the string directly)                      |
| `.append(text)`        | Adds text to the end                                                      | nothing (modifies the string directly), same effect as `+=` |
| `.erase(start, count)` | Removes a chunk of characters starting at `start`, for `count` characters | nothing (modifies the string directly)                      |

All of these operate on the string they're called on, called the string's "instance." Indexes for `.erase()` start at 0, just like arrays.


---

# 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, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/17.-useful-string-methods.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
