String in c++
C Style char
char chr = 'A';
char
implicitly represents the ascii integer value. For example, the character ‘A’ is represented by the ASCII code 65. When you store ‘A’ in a char
variable, it's actually storing the integer value 65.
// Method 1: Using printf with %d format specifier
printf("ASCII value of '%c' is %d\n", ch, ch);
// Method 2: Casting to int and printing
int asciiValue = (int)ch;
printf("ASCII value of '%c' is %d\n", ch, asciiValue);
// Read digit value
printf("Digit value of '%c' is %d\n", ch, ch - '0');
For example, to check if char is digit or not can be done using following.
if(chr >= '0' && chr <= '9') {
cout <<chr <<" is a digit"<<endl;
}
We can also use std::isdigit()
function from <cctype>
to check if char is a digit or not.
if(isdigit(chr)) {
cout <<chr <<" is a digit"<<endl;
}
Following are few useful methods from cctype
isalpha(c)
: Returnstrue
ifc
is an alphabetic character (A-Z or a-z).isdigit(c)
: Returnstrue
ifc
is a digit (0-9).isalnum(c)
: Returnstrue
ifc
is an alphanumeric character (alphabetic or digit).isspace(c)
: Returnstrue
ifc
is a whitespace character (space, tab, newline, etc.).isupper(c)
: Returnstrue
ifc
is an uppercase letter.islower(c)
: Returnstrue
ifc
is a lowercase letter.toupper(c)
: Convertsc
to uppercase if it is a lowercase letter.tolower(c)
: Convertsc
to lowercase if it is an uppercase letter.isxdigit(c)
: Returnstrue
ifc
is a hexadecimal digit (0-9, A-F, or a-f).
C Style string
A C-style string is essentially an array of characters. However, unlike other arrays, it’s not explicitly marked with its length. Instead, the end of the string is indicated by a special character called the null character, which has an ASCII value of 0 and is represented by the character '\0'
.
char str[] = "Hello World!";
Following is code to iterate chars in string.
for (int i = 0; str[i] != '\0'; i++) {
std::cout << str[i] << " ";
}
strstr()
: Finds the first occurrence of a substring within a C-style string. Returns a pointer to the beginning of the found substring, or NULL
if not found.
char str[] = "Hello, world!";
char substr[] = "world";
char* found = strstr(str, substr);
if (found != NULL) {
cout << "Found 'world' at index " << found - str << endl;
} else {
cout << "'world' not found." << endl;
}
string class
We can create string and initialize as below.
string str = "Hello, world!";
string str(5,'A'); // Creates AAAAA
string str(other_str);// copy constructor
Access char
We can access char of string as below.
char c = str[3]; // access 4th char
Modify string
str.append(" there"); // Append a string
str.insert(5, "beautiful"); // Insert at index 5th
str.erase(5,2); // erase two chars starting at index 5th
str.replace(0,5,"Good bye"); // Replace chars from 0 ending at 5(excluding)
Length and comparison
int len = str.size(); // str.length() also exist
bool eq = str == other_string;
bool less = str < other_string;
reverse api
reverse()
Method: Use string being and end pointer to reverse the string
string str = "Hello, world!";
reverse(str.begin(), str.end()); // mutate str
find api
find()
: Finds the first occurrence of a substring within the string. Returns the starting index of the substring if found, otherwise std::string::npos
. Can optionally specify the starting position for the search.
string str = "Hello, world!";
int pos = str.find("world");
if (pos != string::npos) {
cout << "Found 'world' at index " << pos << endl;
} else {
cout << "'world' not found." << endl;
}
rfind()
: Finds the last occurrence of a substring within the string. Returns the starting index of the substring if found, otherwise std::string::npos
. Can optionally specify the starting position for the search.
string str = "Hello, world, world!";
int pos = str.rfind("world");
if (pos != string::npos) {
cout << "Found 'world' at index " << pos << endl;
} else {
cout << "'world' not found." << endl;
}
find_first_of()
: Finds the first occurrence of any character from a given set within the string. Returns the starting index of the found character, otherwise std::string::npos
.
string str = "Hello, world!";
int pos = str.find_first_of("aeiou");
if (pos != string::npos) {
cout << "First vowel found at index " << pos << endl;
} else {
cout << "No vowels found." << endl;
}
find_last_of()
: Finds the last occurrence of any character from a given set within the string. Returns the starting index of the found character, otherwise std::string::npos
.
string str = "Hello, world!";
int pos = str.find_last_of("aeiou");
if (pos != string::npos) {
cout << "Last vowel found at index " << pos << endl;
} else {
cout << "No vowels found." << endl;
}
Clear api
str.clear();
str.empty();
Substring api
substr()
Method: Extracts a substring from a given position and length. Takes two arguments:
- Starting index (inclusive)
- Length of the substring (optional)
string str = "Hello world!!";
string token1 = str.substr(5); // index 5 to the end
string token2 = str.substr(5,2); // index 5 to 6 (length 2)
Iterate string
str.begin();
str.end();
str.rbegin();
str.rend();
Following are few example
for (int i = 0; i < str.length(); i++) {
std::cout << str[i] << " ";
}
// Iterating using begin() and end()
for (string::iterator it = str.begin(); it != str.end(); ++it) {
cout << *it << " ";
}
// Iterate using for-each style
for (char chr : str) {
cout << chr << " ";
}
Note: Iterating or reading string at given index returns char
therefore be careful.
Conversion
Following are ways to convert a string representation of a number into an actual numerical value.
for integers
std::stoi
: Converts to anint
.std::stol
: Converts to along
.std::stoll
: Converts to along long
.
They throw exceptions (std::invalid_argument
or std::out_of_range
) if the conversion fails.
string str = "12345";
int num = stoi(str);
cout << num << endl; // Output: 12345
for floating-point numbers
std::stof
: Converts to afloat
.std::stod
: Converts to adouble
.std::stold
: Converts to along double
.
string str = "3.14159";
double num = stod(str);
cout << num << endl; // Output: 3.14159
Convert number to string
std::to_string(): convert numerical types (int, float, double, etc.) to strings.
int age = 30;
double price = 19.99;
string ageString = to_string(age); // "30"
string priceString = to_string(price); // "19.99"
Convert char to string
If we use std::to_string()
for char
then first it will convert char
into corresponding ascii value then convert integer into string. Following is buggy code.
char chr = 1;
cout << to_string(chr); // It will print 49 as ascii value
To convert char
to string we can take following approach.
char chr = 1;
string str = {chr};
cout << str; // It will print 1
String concatenation
The +
Operator
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
The +=
Operator
string message = "Hello";
message += ", world!";
std::string::append()
: Offers variations for appending parts of strings or a specified number of characters.
string str1 = "Hello";
string str2 = " world!";
str1.append(str2);
cout << str1 << endl;
// Output: Hello world!
Sort string
The most efficient and straightforward way to sort a string in C++ is by using the std::sort
function from the <algorithm>
header. This function takes iterators to the beginning and end of the range to be sorted. For strings, these iterators are typically begin()
and end()
.
int main() {
string str = "hello world";
// Sort the string in ascending order
sort(str.begin(), str.end());
cout << str << std::endl; // Output: dehllloorw
return 0;
}
Split operation
C++ doesn’t have native .split()
methon on string. We will have to write our own as below.
Approach #1: Using stringstream and getline
#include <bits/stdc++>
using namespace std
vector<string> split(const string& str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
string str = "apple,banana,cherry";
char delimiter = ',';
vector<string> result = split(str, delimiter);
for (const auto& token : result) {
cout << token << endl;
}
return 0;
}
Good for: Simple cases with single-character delimiters.
How it works:
- Create a
std::stringstream
from your string. - Use
std::getline
with the delimiter to extract substrings into a container (e.g., astd::vector
).
Approach #2: Manual Splitting with find and string::substr
Good for: More control and flexibility, especially with multi-character delimiters.
How it works:
- Repeatedly use
find
to locate the delimiter in the string. - Extract the substring before the delimiter using
string::substr
.
#include <bits/stdc++>
using namespace std
vector<string> split(const string& str, const string& delimiter) {
vector<string> tokens;
size_t prev = 0, pos = 0;
do {
pos = str.find(delimiter, prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + delimiter.length();
} while (pos < str.length() && prev < str.length());
return tokens;
}
int main() {
string str = "apple::banana::cherry";
string delimiter = "::";
vector<string> result = split(str, delimiter);
for (const auto& token : result) {
cout << token << endl;
}
return 0;
}
More about stringstream
- It’s a class in the
<sstream>
header file. - It lets you treat a string like an input/output stream, similar to how you use
std::cin
(for keyboard input) andstd::cout
(for console output). - This means you can use stream operators (
<<
for insertion,>>
for extraction) with strings.
#include <bits/stdc++>
using namespace std
int main() {
stringstream ss;
int num = 123;
// Convert int to string
ss << num;
string strNum = ss.str();
cout << "String: " << strNum << endl;
// Clear the stringstream
ss.str("");
ss.clear();
// Convert string to int
string str = "456";
ss << str;
ss >> num;
cout << "Number: " << num << endl;
return 0;
}
More on getline
#include <bits/stdc++>
using namespace std
int main() {
string name;
cout << "Enter your full name: ";
getline(cin, name);
cout << "Hello, " << name << "!\n";
string data = "apple;banana;cherry";
stringstream ss(data);
string item;
while (getline(ss, item, ';')) {
cout << item << endl;
}
return 0;
}
Example to use stringstream to repeat string
#include <iostream>
#include <string>
#include <sstream>
std::string repeat_string(const std::string& str, int n) {
std::stringstream ss;
for (int i = 0; i < n; ++i) {
ss << str;
}
return ss.str();
}
Happy learning c++ :)