String Manipulation Functions
1. Concatenation
Combines two strings into one.
Syntax:
string result = str1 + str2; // Using '+' operator
str1 += str2; // Append str2 to str1
Example:
string str1 = "Hello, ";
string str2 = "World!";
string result = str1 + str2; // "Hello, World!"
str1 += "C++"; // "Hello, C++"
2. Substring
Extracts a portion of a string.
Syntax:
string substr = [Link](start, length);
Example:
string str = "Hello, World!";
string substr = [Link](7, 5); // "World"
3. Find
Locates the position of a substring or character.
Syntax:
size_t pos = [Link]("substring");
size_t pos = [Link]('c');
Example:
string str = "Hello, World!";
size_t pos = [Link]("World"); // 7
if (pos != string::npos) {
cout << "Found at position " << pos;
}
4. Insert
Inserts a substring into the string.
Syntax:
[Link](position, "substring");
Example:
string str = "Hello!";
[Link](5, ", World"); // "Hello, World!"
5. Erase
Removes part of the string.
Syntax:
[Link](start, length);
Example:
string str = "Hello, World!";
[Link](5, 7); // "Hello!"
6. Compare
Compares two strings lexicographically.
Syntax:
int result = [Link](str2);
Returns 0 if str1 == str2.
o
Returns <0 if str1 < str2.
o
Returns >0 if str1 > str2.
o
Example:
string str1 = "abc";
string str2 = "def";
int result = [Link](str2); // -1 (since "abc" < "def")
7. Replace
Replaces a portion of the string with another substring.
Syntax:
[Link](start, length, "new substring");
Example:
string str = "Hello, World!";
[Link](7, 5, "C++"); // "Hello, C++!"
8. Length
Returns the number of characters in the string.
Syntax: size_t len = [Link]();
Example: string str = "Hello!";
size_t len = [Link](); // 6
9. Empty
Checks if the string is empty.
Syntax: bool isEmpty = [Link]();
Example:
string str = "";
if ([Link]()) {
cout << "String is empty!";
}
10. Swap
Swaps the contents of two strings.
Syntax: [Link](str2);
Example:
string str1 = "Hello";
string str2 = "World";
[Link](str2); // str1 = "World", str2 = "Hello"
Summary
Syntax
Function Purpose
Example
Concatenation Combine two strings str1 + str2 or str1 += str2
Substring Extract part of a string [Link](start, length)
Find Locate substring or character [Link]("sub")
[Link](pos,
Insert Add substring at a position "sub")
[Link](start,
Erase Remove part of a string length)
Compare Compare two strings [Link](str2)
[Link](start,
Replace Replace part of a string len, "new")
Length Get the length of a string [Link]()
Empty Check if string is empty [Link]()
Swap Swap two strings [Link](str2)