String Functions in C++ (original) (raw)

String is a sequence of characters used to represent and manipulate text data efficiently. The C++ Standard Library provides the std::string class, which offers powerful built-in functionality for string operations.

#include #include using namespace std;

int main() {

// Creating a string
string str = "Hello World";

// Display original string
cout << "Original String: " << str << endl;

// Find length of string
cout << "Length: " << str.length() << endl;

// Append text
str.append(" !!!");
cout << "After Append: " << str << endl;

// Access character
cout << "First Character: " << str[0] << endl;

// Find a word
cout << "Position of World: " << str.find("World") << endl;

return 0;

}

`

Output

Original String: Hello World Length: 11 After Append: Hello World !!! First Character: H Position of World: 6

Standard String Class in C++

The std::string class in C++ (introduced in C++98) provides a standard and efficient way to represent and manipulate text data. It is defined in the <string> header file and supports a wide range of built-in string operations.

Commonly Used String Functions in C++

String Length - length() or size()

In C++, the length of a string can be determined using either the length() or size() member function of the std::string class. Both functions work identically and return the total number of characters present in the string.

**Syntax

str.length();

str.size();

#include #include using namespace std;

int main() { string text = "GeeksforGeeks";

cout << "String: " << text << endl;
cout << "Length using length(): " << text.length() << endl;
cout << "Length using size(): " << text.size() << endl;

return 0;

}

`

Output

String: GeeksforGeeks Length using length(): 13 Length using size(): 13

Accessing Characters - at()

In C++, characters of a string can be accessed using the array subscript operator ([]) or the at() function provided by the std::string class. The at() function is preferred in many cases because it performs bounds checking and helps avoid invalid memory access.

**Syntax

str.at(index);

#include #include using namespace std;

int main() { string text = "GeeksforGeeks";

cout << "String: " << text << endl;
cout << "Character at index 3: " << text.at(3) << endl;

return 0;

}

`

Output

String: GeeksforGeeks Character at index 3: k

Concatenating Strings - append() or + Operator

In C++, strings can be concatenated using either the + operator or the append() function provided by the std::string class. Both methods are commonly used to join two or more strings into a single string.

**1. + Operator

The + operator is overloaded in the std::string class to support string concatenation. It joins two strings and returns a new combined string.

**Syntax

str1 + str2;

The + operator is used to concatenate two strings. The resulting string fullName will be "GeeksforGeeks Hello".

C++ `

#include #include using namespace std;

int main() { string str1 = "GeeksforGeeks"; string str2 = " Hello";

string fullName = str1 + str2;

cout << "Concatenated String: " << fullName << endl;

return 0;

}

`

Output

Concatenated String: GeeksforGeeks Hello

**2. append() Function

The append() function is a member function of std::string used to add one string to the end of another.

**Syntax

str1.append(str2);

#include #include using namespace std;

int main() { string str1 = "GeeksforGeeks"; string str2 = " Hello";

str1.append(str2);

cout << "Concatenated String: " << str1 << endl;

return 0;

}

`

Output

Concatenated String: GeeksforGeeks Hello

String Comparison - compare() or == Operator

In C++, strings can be compared using either the == operator or the compare() function of the std::string class. Both methods are used to check equality or lexicographical order between two strings.

**1. == Operator

The equality operator (==) is overloaded in the std::string class to compare two strings for equality.

**Syntax

str1 == str2;

This returns true if both strings are equal, otherwise it returns false.

#include #include using namespace std;

int main() { string str1 = "Hello"; string str2 = "Hello";

if (str1 == str2)
    cout << "Strings are equal";
else
    cout << "Strings are not equal";

return 0;

}

`

**2. compare() Function

The compare() function is a member function of std::string used for lexicographical comparison between strings.

**Syntax

str1.compare(str2);

**Parameters: str2 - The string to be compared; it can be a C-style or C++ string.

**Return Value

#include #include using namespace std;

int main() { string str1 = "Apple"; string str2 = "Banana";

int result = str1.compare(str2);

cout << "Result: " << result;

return 0;

}

`

Searching - find()

The find() function in C++ is used to search for a character or substring inside a string. It returns the position of the first occurrence if the element is found.**find() function of the std::string class to check whether a given character or a substring is present in the string or a part of string.

**Syntax:

str.find(var);

**Parameters: var - It can be a C style string, C++ style string, or a character that is to be searched in the string.

**Return Value

The position variable will contain 4, which is the starting index of the first occurrence of "Programming" in the string text.

C++ `

#include #include using namespace std;

int main() { string text = "C++ Programming";

size_t position = text.find("Programming");

cout << "Position: " << position;

return 0;

}

`

Generate Substring - substr()

The substr() function in C++ is used to extract a portion of a string and return it as a new std::string object. It is a member function of the std::string class.

**Syntax

str.substr(start, length);

**Parameters

**Return Type Returns a new std::string object containing the extracted substring

C++ `

#include #include using namespace std;

int main() { string text = "Hello World";

string sub = text.substr(6, 5);

cout << "Substring: " << sub;

return 0;

}

`

Modifying Strings

C++ provides several member functions in the std::string class to modify existing strings efficiently.

insert()

The insert() function is used to insert a string at a specified position within an existing string.

**Syntax

str1.insert(index, str2);

**Parameters

**Return Type: Returns a reference to the modified string (str1)

C++ `

#include #include using namespace std;

int main() { string str1 = "GeeksGeeks"; string str2 = "for";

str1.insert(5, str2);

cout << "Updated String: " << str1;

return 0;

}

`

Output

Updated String: GeeksforGeeks

replace()

The replace() function replaces the part of the string with the given other string. Unlike insert, the characters in the part where the new string is to be inserted are removed.

**Syntax

str1.replace(index, size, str2);

**Parameters

**Return Type: Returns a reference to the modified string (str1)

C++ `

#include #include using namespace std;

int main() { string str1 = "I love Java"; string str2 = "C++";

str1.replace(7, 4, str2);

cout << "Updated String: " << str1;

return 0;

}

`

Output

Updated String: I love C++

3. erase()

The erase() function is a member function of std::string class that is used to remove a character or a part of the string.

**Syntax

str1.erase(start, end);

**Parameters

**Return Type: Returns a reference to the modified string (str1)

C++ `

#include #include using namespace std;

int main() { string str1 = "Hello World";

str1.erase(5, 6);

cout << "Updated String: " << str1;

return 0;

}

`

Output

Updated String: Hello

Converting std::string to C-Style String – c_str()

The c_str() function is a member of the std::string class used to convert a C++ string into a C-style string (null-terminated character array). It is commonly used when working with C library functions that require character pointers.

Syntax

str.c_str();

**Parameters: This function does not take any parameter.

**Return Value: Returns a pointer to a null-terminated character array equivalent of the string

C++ `

#include #include using namespace std;

int main() { string str = "Hello World";

const char* cstr = str.c_str();

cout << "C-style string: " << cstr;

return 0;

}

`

Output

C-style string: Hello World

Standard String Operations in C++ (std::string)

The std::string class provides a rich set of built-in functions for performing common string operations. The table below summarizes the most frequently used functions.

Category Functions and Operators Functionality
String Length length() or size() It will return the length of the string.
Accessing Characters Indexing (using array[index]) To access individual characters using array indexing.
at() Used to access a character at a specified index.
Appending and Concatenating Strings + Operator + operator is used to concatenate two strings.
append() The append() function adds one string to the end of another.
String Comparison == Operator You can compare strings using the == operator.
compare() The compare() function returns an integer value indicating the comparison result.
Substrings substr() Use the substr() function to extract a substring from a string.
Searching find() The find() function returns the position of the first occurrence of a substring.
Modifying Strings replace() Use the replace() function to modify a part of the string.
insert() The insert() function adds a substring at a specified position.
erase() Use the erase() function to remove a part of the string.
Conversion c_str() To obtain a C-style string from a std::string, you can use the c_str() function.

**Note: The above functions only works for C++ Style strings (std::string objects) not for C Style strings (array of characters).