String & Char in C++
String and Character
String
"a"-> This is a string literal of type const char* (C-style string includes βaβ and β\0β)- Type:
const char* - Represents ->
{'a', '\0'}in memory
Null Terminator
'\0'β null terminator- Type:
char - ASCII value 0 -> Marks end of C-style string
Char
'a'β This is a character literal- Type:
char - Represents ASCII value of
'a' = 97
CASTING
Section titled βCASTINGβ| From β To | Conversion |
|---|---|
| string β int | stoi(s) |
| char β int | ch - '0' |
| int β string | to_string(num) |
| int β char | num + '0' |
| string β char | s[0] |
| char β string | s(1, ch) |
Comparing String and Character
// char == Stringif(s[i] == " ") ; // β Invalid : Compile error
// char == Charif(s[i] == ' ') ; // β
Valid
// Note: comparing a character (`s[i]`) with a string (`" "`), and in C or C++, a string literal (like `" "`) is treated as a `const char *` (a pointer to characters), while `s[i]` is a single `char`. These two types are not directly comparable."a" == 'a' // β Invalid : Comparing pointer with char// "a" is a string literal (const char*) β address of first character// 'a' is a char β ASCII value 97"a"[0] == 'a' //β
Valid & True// "a"[0] is the first character of string literal β 'a'"a" = 'a\0' // β Inalid : A character literal can not represent more than one character// 'a\0' is an invalid char literal (char can only hold one character)// Also, "a" is a string literal β cannot be assigned to (it's const char*) β βFix -> Casting β
char->stringCasting
char ch = 'a';string s(1, ch); // β
creates string "a"// Equivalent: string s = string(1, ch);string(size_t n, char c)constructor creates a string ofncopies of characterc.
string->charCasting
string s = "a";char ch = s[0]; // β
extracts first character
s[1] == '\0' ? // β Not guaranteed in std::stringstd::stringis not null-terminated like C-style strings.- Accessing
s[1]is undefined behavior ifs.size() == 1.
Notes:
string s(1, ch)creates a string of length 1 with charchs[0]gives the first character of the string- Ensure
s.length() >= 1before accessings[0]to avoid error
Comparing Number and String
string s = "5";if (s == 5) // β Error: invalid comparisonFix -> Casting β
string->num
int num = stoi(s); // stoi β string to intif (num == 5) // β
valid- Throw
std::invalid_argumentβ if the string is not a number at all - Throw
std::out_of_rangeβ if the number is too large forint
num->string
int x = 5;string s = to_string(x);Comparing Number and Character
char ch = '5';if (ch == 5) // β
valid but, β Not logical// compares ASCII: '5' = 53 β 5Fix -> Casting β
char->int
int num = ch - '0'; // '5' - '0' = 5int->char
char ch = x + '0'; // 5 + '0' = '5'Notes on stringstream in C++
#include <sstream>Purpose - stringstream is used for parsing and manipulating strings like a stream (similar to cin, cout).
Declaration:
stringstream ss;Initialize with string:
string str = "hello world";stringstream ss(str);Extract words from string:
string word;while (ss >> word) { // each word in 'word'}Convert string to int / double: β
string s = "123";stringstream ss(s);int x;ss >> x; // x = 123
s >> x; // β Error: 's' is a string, not a streamConvert int to string:
int x = 456;stringstream ss;ss << x;string s = ss.str(); // s = "456"
s << x; // β Error: 's' is a string, not a streamFunctions:
ss.str()β returns full string content.ss.clear()β clears error flags (for reuse).ss.str("")β resets/clears the buffer.
Common Use Cases:
- Tokenizing strings
- Type conversion (string β number)
- Parsing CSV or space-separated data
Example:
string s = "10 20 30";stringstream ss(s);int num;while (ss >> num) { cout << num << " ";}// Output: 10 20 30String Reverse
built-in reverse function from the <algorithm> library.
reverse(str.begin(), str.end());
constructs a new string using reverse iterators (rbegin and rend)
string reversed_str(str.rbegin(), str.rend());
Concatenate character with string
std::string str = "Hello";
str += '!';# orstr.push_back('!');
# Both methods will result in the string `"Hello!"`.Seperate words
std::string str = "Hello World";size_t spacePos = str.find(' '); // Finds the position of the spacestd::string hello = str.substr(0, spacePos); // Extracts "Hello"std::string world = str.substr(spacePos + 1); // Extracts "World"Reverse Word using #include <sstream> β
Store each words of string s in vector;
// Split the string into wordsistringstream iss(s);while (iss >> str){ //input word vec.push_back(str);}Concatenate words from vector to string str in revers Order
// Reverse the order of words ostringstream oss;for (int i = vec.size() - 1; i >= 0; --i){ oss << vec[i]; if (i > 0){ oss << " "; }}istringstream: Used to split the input stringsinto words. It allows you to extract words one by one using the>>operator.- Used to read data from a string, similar to how
ifstreamis used to read from a file. You can use it to extract formatted data from a string. ostringstream: Used to build the final result string with the words in reversed order. It provides efficient string concatenation and formatting.- Used to write data to a string, similar to how
ofstreamis used to write to a file. You can use it to format and assemble a string from various data types.
substr()
Section titled βsubstr()β-
Purpose: Extracts a substring from a string.
-
Syntax:
string substr(size_t pos, size_t len)pos: Starting index.len: Number of characters to extract.
-
Example:
string s = "Hello World";string sub = s.substr(6, 5); // "World" -
If
lenexceeds the string length, it extracts until the end.
- Returns character at given
index - Performs bounds checking
- Throws
std::out_of_rangeif index is invalid
Example:
string s = "Gaurav";char ch = s.at(2); // 'u'Difference s[index] vs s.at(index) ?
s[index]is faster but no bounds checkings.at(index)is safer for error handling
Is string part of STL?
Section titled βIs string part of STL?βstd::stringis part of the C++ Standard Library- It is not part of the original STL (Stepanov STL)
- It is implemented as
std::basic_string<char> - Practically behaves like a dynamic container
Conclusion:
In CP & interviews β Treat string as STL container.
1. STL-like Container Functions
- Capacity:
s.size(),s.length(),s.empty(),s.capacity(),s.reserve(n),s.shrink_to_fit(),s.max_size(); - Element Access:
s[i],s.at(i),s.front(),s.back() - Modifiers:
s.push_back(c),s.pop_back(),s.clear(),s.insert(pos, str),s.erase(pos, len),s.replace(pos, len, str),s.append(str),s += str,s.swap(other),s.resize(n); - Iterators:
s.begin(),s.end(),s.rbegin(),s.rend(),s.cbegin(),s.cend(),s.crbegin(),s.crend()
2. String-Specific Functions (Non-STL style)
- Substring:
s.substr(pos, len) - Find Operations:
s.find(str),s.rfind(str),s.find_first_of(chars),s.find_last_of(chars),s.find_first_not_of(chars),s.find_last_not_of(chars) - Comparison:
s.compare(str) - Copy:
s.copy(arr, len, pos)
4. Conversion Functions (Non-member)
- String β Number:
stoi(s),stol(s),stoll(s),stof(s),stod(s) - Number β String:
to_string(num)
5. C-style Interoperability:
s.c_str(),s.data()
6. Relational Operators:
==,!=,<,>,<=,>=- Lexicographical comparison.
Important Properties β’ Dynamic size
β’ Contiguous memory
β’ O(1) random access
β’ Works with STL algorithms