C++ String Functions (length, append, find)

The std::string class in C++ provides many built-in member functions to manipulate strings easily. Among the most commonly used are length(), append(), and find().

1. length() Function

The length() function returns the number of characters in a string.

C++
Example: Using length()
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello World";
    cout << "Length of string: " << str.length();
    return 0;
}

2. append() Function

The append() function adds characters or another string to the end of the current string.

C++
Example: Using append()
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello";
    str.append(" World");
    cout << str;
    return 0;
}

3. find() Function

The find() function searches for a substring or character in a string and returns its position. If not found, it returns string::npos.

C++
Example: Using find()
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Welcome to C++ Programming";
    size_t position = str.find("C++");

    if (position != string::npos) {
        cout << "Substring found at position: " << position;
    } else {
        cout << "Substring not found";
    }

    return 0;
}

4. Important Notes

1. length() and size() functions return the same value. 2. append() modifies the original string. 3. find() returns the index of the first occurrence. 4. Always check against string::npos when using find().

Conclusion

The length(), append(), and find() functions are essential for string manipulation in C++. They provide efficient and easy ways to measure, modify, and search within strings.