Introduction to C++ | Strings
Strings in C++
In C++, a string is a sequence of characters that represents text. C++ provides two primary ways to handle strings:
the traditional C-style strings (arrays of characters) and the C++ std::string
class, which is more modern and easier to use.
What is a String in C++?
A string is a collection of characters stored sequentially. In C++, you can use both:
- C-style strings: These are arrays of characters terminated with a null character `'0'`.
- C++ strings: The
std::string
class in C++ offers more flexibility and easier operations.
C-Style String
A C-style string is an array of characters with a null terminator (`'0'`) at the end. You can define a C-style string as follows:
Code Example: C-Style String
#include <iostream>
using namespace std;
int main() {
char str[] = "Hello, World!"; // C-style string
cout << "String: " << str << endl;
return 0;
}
Output
C++ String Class
The std::string
class in C++ provides a more flexible and easier-to-use way to handle strings. It is part of the C++ Standard Library and allows you to perform many string-related operations without having to worry about memory management and null-terminators.
Code Example: C++ String
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, C++ World!"; // C++ string
cout << "String: " << str << endl;
return 0;
}
Output
C++ String Functions
Function | Description |
---|---|
int compare(const string& str) | Used to compare two string objects. |
int length() | Used to find the length of the string. |
void swap(string& str) | Swaps the values of two string objects. |
string substr(int pos, int n) | Creates a new string object of `n` characters starting from position `pos`. |
int size() | Returns the length of the string in terms of bytes. |
void resize(int n) | Resizes the length of the string to `n` characters. |
string& replace(int pos, int len, string& str) | Replaces a portion of the string starting at position `pos` and spanning `len` characters with another string. |
string& append(const string& str) | Adds new characters at the end of another string object. |
char& at(int pos) | Accesses an individual character at the specified position `pos`. |
int find(string& str, int pos, int n) | Finds the string specified in the parameter. |
int find_first_of(string& str, int pos, int n) | Finds the first occurrence of the specified sequence. |
int find_first_not_of(string& str, int pos, int n) | Searches the string for the first character that does not match any of the characters specified in the string. |
int find_last_of(string& str, int pos, int n) | Searches the string for the last character of the specified sequence. |
int find_last_not_of(string& str, int pos) | Searches for the last character that does not match with the specified sequence. |
string& insert() | Inserts a new character before the character indicated by the position `pos`. |
int max_size() | Finds the maximum length of the string. |
void push_back(char ch) | Adds a new character `ch` at the end of the string. |
void pop_back() | Removes the last character of the string. |
string& assign() | Assigns a new value to the string. |
int copy(string& str) | Copies the contents of a string into another. |
char& back() | Returns the reference of the last character. |
Iterator begin() | Returns the reference to the first character of the string. |
int capacity() | Returns the allocated space for the string. |
const_iterator cbegin() | It points to the first element of the string. |
Common String Operations in C++
- Concatenation: You can concatenate strings using the
+
operator. - Length: You can get the length of a string using the
length()
orsize()
function. - Comparison: Strings can be compared using comparison operators like
==
,<
, etc. - Accessing Characters: You can access individual characters of a string using the index (e.g.,
str[0]
). - Substring: You can extract a portion of a string using the
substr()
function. - Appending: You can append another string or character using the
append()
function or+=
operator. - Inserting: You can insert a substring at a specific position using the
insert()
function. - Erasing: You can erase a part of a string using the
erase()
function. - Finding: You can search for a substring or character within a string using the
find()
function. - Replacing: Replace a part of the string using the
replace()
function. - Converting to C-String: You can get a C-style string (null-terminated char array) using the
c_str()
function. - Empty Check: Check if a string is empty using the
empty()
function. - Clearing: You can clear the entire string using the
clear()
function. - Swapping: Swap the contents of two strings using the
swap()
function. - Character Count: Count occurrences of a character using a loop or standard algorithms.
Example: 1.String Initialization
Code Example: String Initialization
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "C++ Programming";
string emptyStr;
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
cout << "Empty String: " << emptyStr << endl;
return 0;
}
Output
String 2: C++ Programming
Empty String:
Example: 2.Concatenation and Length
Code Example: Concatenation and Length
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "World!";
// Concatenation
string result = str1 + ", " + str2;
// Length
int length = result.length();
cout << "Concatenated String: " << result << endl;
cout << "Length of the String: " << length << endl;
return 0;
}
Output
Length of the String: 13
Example: 3.Appending Strings
Code Example: Appending Strings
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
str.append(", World!");
cout << "Appended String: " << str << endl;
return 0;
}
Output
Example: 4 Accessing Characters
Code Example: Accessing Characters
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "C++ Programming";
cout << "First Character: " << str[0] << endl;
cout << "Last Character: " << str[str.length() - 1] << endl;
return 0;
}
Output
Last Character: g
Example: 5.Finding Substring
Code Example: Finding Substring
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Programming in C++";
size_t pos = str.find("C++");
if (pos != string::npos) {
cout << "'C++' found at position: " << pos << endl;
} else {
cout << "'C++' not found." << endl;
}
return 0;
}
Output
Example: 6.Replacing Substring
Code Example: Replacing Substring
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
str.replace(7, 5, "C++");
cout << "Modified String: " << str << endl;
return 0;
}
Output
Example: 7.Inserting Substring
Code Example: Inserting Substring
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello!";
str.insert(5, ", World");
cout << "Modified String: " << str << endl;
return 0;
}
Output
Example: 8.Erasing Characters
Code Example: Erasing Characters
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
str.erase(5, 7);
cout << "Modified String: " << str << endl;
return 0;
}
Output
Example: 9.String Capacity
Code Example: String Capacity
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, C++!";
// Initial capacity
cout << "Initial Capacity: " << str.capacity() << endl;
// Adding more characters to exceed capacity
str += " Let's learn string operations.";
cout << "New Capacity after modification: " << str.capacity() << endl;
// Reserving more capacity
str.reserve(100);
cout << "Capacity after reserve: " << str.capacity() << endl;
return 0;
}
Output
New Capacity after modification: 31
Capacity after reserve: 100
Example: 10.Reversing a String
Code Example: Reversing a String
#include <iostream>
#include <string>
#include <algorithm> // for reverse()
using namespace std;
int main() {
string str = "Hello, World!";
// Reverse the string
reverse(str.begin(), str.end());
cout << "Reversed String: " << str << endl;
return 0;
}
Output
Pro Tip:
💡 Pro Tip
When using strings in C++, the std::string
class is preferred because it is more flexible and easier to use than C-style strings. C++ strings handle memory automatically, reducing the risk of memory errors.