Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views6 pages

C++ String Manipulation

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

C++ String Manipulation

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

C++ String Manipulation

9 forms of initialization
C++ 11

The std::string class provides 9 forms of constructors (initialization methods) to create and initialize strings. Each form offers
different ways to initialize a std::string object based on the type and structure of the input. Here's a detailed explanation of
each form:

1. Default Constructor

std::string();

Creates an empty string.


No content is assigned to the string; its size is 0.
Example:

std::string str; // Empty string

2. Constructor with a Copy of a C++ String

std::string(const std::string& str);

Creates a new string as a copy of an existing std::string .


Example:

std::string str1 = "Hello";


std::string str2(str1); // str2 = "Hello"

3. Constructor with a Substring of a C++ String

std::string(const std::string& str, size_t pos, size_t len = npos);

Initializes a string as a substring of another std::string .


pos : Starting position of the substring in str .
len : Maximum number of characters to include (default is npos , meaning "to the end").
If pos is out of bounds, it throws std::out_of_range .
Example:

std::string str1 = "Hello, World!";


std::string str2(str1, 7, 5); // str2 = "World"

4. Constructor from a C-Style String (Null-Terminated Character Array)

std::string(const char* s);


Creates a string by copying the contents of a null-terminated C-style string.
Example:

const char* cstr = "C++";


std::string str(cstr); // str = "C++"

5. Constructor from a Subset of a C-Style String

std::string(const char* s, size_t n);

Initializes a string by copying the first n characters from the C-style string s .
Does not require s to be null-terminated.
Example:

const char* cstr = "C++ Programming";


std::string str(cstr, 3); // str = "C++"

6. Fill Constructor

std::string(size_t n, char c);

Creates a string of length n filled with the character c .


Example:

std::string str(5, 'A'); // str = "AAAAA"

7. Range Constructor

template <class InputIterator>


std::string(InputIterator first, InputIterator last);

Creates a string by copying characters from the range [first, last) provided by iterators.
Useful for creating a string from part of a container like std::vector<char> or std::deque<char> .
Example:

std::vector<char> vec = {'H', 'e', 'l', 'l', 'o'};


std::string str(vec.begin(), vec.begin() + 3); // str = "Hel"

8. Move Constructor

std::string(std::string&& str) noexcept;

Transfers the content of an existing string to a new string without making a copy (move semantics).
The original string ( str ) is left in a valid but unspecified state (usually empty).
Example:

std::string str1 = "Hello";


std::string str2 move(str1) ; // str2 = "Hello", str1 is now empty

9. Initializer List Constructor

std::string(std::initializer_list<char> il);

Creates a string from a list of characters.


Example:

std::string str({'H', 'e', 'l', 'l', 'o'}); // str = "Hello"

Summary Table

Constructor Description
std::string() Default constructor (empty string).
Constructor Description
std::string string& Copy constructor from another std::string .
std::string string&, size_t pos, size_t len = npos Substring constructor from another std::string .
std::string(const char*) From a null-terminated C-style string.
std::string(const char*, size_t) From the first n characters of a C-style string.
std::string(size_t, char) Fill constructor (string of n repeated characters).
std::string(InputIterator, InputIterator) Range constructor (from iterators).
std::string string&& Move constructor string .
std::string initializer_list<char> From an initializer list of characters.

These constructors offer flexibility for creating std::string objects for different situations, ranging from basic initialization to
advanced usage scenarios like iterators and move semantics.

String Operations Analysis


Comprehensive ranking of time and space complexity for all commonly used operations on std::string in C++. This ranking
assumes the string has length n , and that the standard implementation uses short string optimization (SSO) for very small
strings.

Notation
n : Length of the string
m : Length of argument string (when relevant)
Most functions are amortized unless stated otherwise

Access & Size Operations

Operation Time Complexity Space Complexity Notes


s.size() , s.length() O(1) O(1) Just returns cached size
s.capacity() O(1) O(1) Returns allocated capacity
s.empty() O(1) O(1)
s[i] , s.at(i) O(1) O(1) Bounds-checked if .at()

Modification Operations

Operation Time Complexity Space Complexity Notes


s.push_back(c) Amortized O(1) Amortized O(1) May cause reallocation
s.pop_back() O(1) O(1) No reallocation
s += other_string O(m) O(n + m) Reallocates if needed
s.append(str) O(m) O(n + m) Similar to +=
s.insert(pos, str) O(n + m) O(n + m) Moves data to make space
s.erase(pos, len) O(n) O(n) Shifts tail of string
s.replace(pos, len, str) O(n + m) O(n + m) Replace range with new string
s.clear() O(1) O(1) Keeps capacity
s.resize(new_size) O(n) O(new_size) May truncate or expand
s.reserve(capacity) O(n) O(capacity) Allocates extra space
s.shrink_to_fit() O(n) O(n) Reclaims unused memory
s.swap(other) O(1) O(1) Just swaps pointers

Searching Operations

Operation Time Complexity Space Complexity Notes


s.find(substr) O(n * m) worst O(1) Naive implementation
s.rfind(substr) O(n * m) worst O(1)
Operation Time Complexity Space Complexity Notes
s.find_first_of(chars) O(n * k) O(1) k = size of chars
s.find_last_of(chars) O(n * k) O(1)
s.find_first_not_of(chars) O(n * k) O(1)
s.find_last_not_of(chars) O(n * k) O(1)
s.compare(str) O(min(n, m)) O(1) Lexicographical comparison

Substring and Copy Operations

Operation Time Complexity Space Complexity Notes


s.substr(pos, len) O(len) O(len) Allocates new string
s.copy(dest, len, pos) O(len) O(1) Copies characters to C-array
std::getline() O(n) O(n) Reads until newline

Conversion and I/O

Operation Time Complexity Space Complexity Notes


Stream input/output ( << , >> ) O(n) O(n) Based on number of characters
std::stoi , std::stod , etc. O(n) O(1) Parses the string

Comparison and Equality

Operation Time Complexity Space Complexity Notes


s == t , s < t O(min(n, m)) O(1) Stops at first mismatch

Ranked Summary (Time Complexity)


O(1): size() , empty() , operator[] , push_back() , pop_back() , swap()
O(n): resize() , clear() , copy() , getline()
O(n + m): insert() , replace() , append() , operator+=
O(n * m): find() , rfind() (worst case)

Char Manipulation
Check chars ( <cctype> )
🔧 These come from <cctype> ( #include <cctype> )

Case & Letter

std::isalpha(c); // True if letter (a-z or A-Z)


std::isupper(c); // True if uppercase
std::islower(c); // True if lowercase

Digit & Number

std::isdigit(c); // True if 0-9


std::isxdigit(c); // True if hexadecimal digit (0-9, a-f, A-F)

Other types

std::isalnum(c); // True if alphanumeric (letter or digit)


std::isspace(c); // True if whitespace (space, tab, newline, etc.)
std::ispunct(c); // True if punctuation (e.g., !, ?, ,)
std::isprint(c); // True if printable (excluding control chars)
std::iscntrl(c); // True if control character (e.g., '\n', '\r')
Character Transformation
std::tolower(c); // Convert to lowercase
std::toupper(c); // Convert to uppercase

O(1). These don't change the original c ; they return the result. Assign back if needed.

Specific Checks & Custom Conditions


Is vowel?

bool is_vowel(char c) {
c = std::tolower(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}

Is consonant?

bool is_consonant(char c) {
return std::isalpha(c) && !is_vowel(c);
}

Is specific char (e.g. dot or question mark)?

if (c == '.') { /* do something */ }
if (c == '?') { /* do something */ }

Is letter from a given set?

bool is_from_set(char c, const std::string& set) {


return set.find(c) != std::string::npos;
}

Usage:

is_from_set(c, "aeiou"); // vowel check


is_from_set(c, "!?."); // punctuation group check

Position-based checks in strings


Is first character capitalized?

bool is_capitalized(const std::string& s) {


return !s.empty() && std::isupper(s[0]);
}

Is entire string uppercase/lowercase?

bool is_all_upper(const std::string& s) {


return std::all_of(s.begin(), s.end(), [](char c) {
return !std::isalpha(c) || std::isupper(c);
});
}

bool is_all_lower(const std::string& s) {


return std::all_of(s.begin(), s.end(), [](char c) {
return !std::isalpha(c) || std::islower(c);
});
}
Manipulate Char
Addition
Add 'a' and 'b' together will result in a character of the sum of the ascii values of a and b together

char c1 = 'a'; // ASCII dec: 97


char c2 = 'b'; // ASCII dec: 98
char ans = c1 + c2; // Total ASCII value: 97 + 98 = 195 => out of signed char's limit => garbage or weird value printed

Other Practical Use Cases


Convert whole string to lowercase or uppercase:

std::transform(s.begin(), s.end(), s.begin(), ::tolower); // to lowercase


std::transform(s.begin(), s.end(), s.begin(), ::toupper); // to uppercase

🧪 Want fast inline macros for chars?


You can define simple helpers:

#define IS_VOWEL(c) (strchr("aeiouAEIOU", (c)) != nullptr)


#define IS_CONSONANT(c) (isalpha(c) && !IS_VOWEL(c))

You might also like