Skip to content

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
From β†’ ToConversion
string β†’ intstoi(s)
char β†’ intch - '0'
int β†’ stringto_string(num)
int β†’ charnum + '0'
string β†’ chars[0]
char β†’ strings(1, ch)

Comparing String and Character

// char == String
if(s[i] == " ") ; // ❌ Invalid : Compile error
// char == Char
if(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 βœ…

  1. char -> string Casting
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 of n copies of character c.
  1. string -> char Casting
string s = "a";
char ch = s[0]; // βœ… extracts first character
s[1] == '\0' ? // ❌ Not guaranteed in std::string
  • std::string is not null-terminated like C-style strings.
  • Accessing s[1] is undefined behavior if s.size() == 1.

Notes:

  • string s(1, ch) creates a string of length 1 with char ch
  • s[0] gives the first character of the string
  • Ensure s.length() >= 1 before accessing s[0] to avoid error

Comparing Number and String

string s = "5";
if (s == 5) // ❌ Error: invalid comparison

Fix -> Casting βœ…

  1. string -> num
int num = stoi(s); // stoi β†’ string to int
if (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 for int
  1. 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 β‰  5

Fix -> Casting βœ…

  1. char -> int
int num = ch - '0'; // '5' - '0' = 5
  1. int -> 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 stream

Convert 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 stream

Functions:

  • 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 30

String 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 += '!';
# or
str.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 space
std::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 words
istringstream 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 string s into words. It allows you to extract words one by one using the >> operator.
  • Used to read data from a string, similar to how ifstream is 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 ofstream is used to write to a file. You can use it to format and assemble a string from various data types.

  • 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 len exceeds the string length, it extracts until the end.


  • Returns character at given index
  • Performs bounds checking
  • Throws std::out_of_range if 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 checking
  • s.at(index) is safer for error handling

  • std::string is 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