Arrays & Strings
Strings
Complete lesson for Strings using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with C++ OOP and STL where relevant.
Basics — Strings
Section: Arrays & Strings. C++ strings with std::string — creation, library functions table, and real-life text examples.
What is a string in C++?
- A **string** stores a sequence of characters — names, passwords, sentences, file paths.
- Prefer **
std::string** (#include) for everyday text: dynamic length, safe and rich operations. - Older **C-strings** are
chararrays ending with'\0'— still appear in APIs; harder to manage by hand. - **Real-life examples:** student name, email ID, OTP code, product SKU, chat message.
| Idea | Meaning | Real-life mapping |
|---|---|---|
| Characters | Letters / digits / symbols | Letters in a name |
| Length | How many characters | Password must be ≥ 8 |
| Index | Position from 0 | First letter of a name |
| Empty string | "" — length 0 | Blank form field |
Creating and using std::string
- Declare:
string name;orstring name = "Ravi"; - Read a word:
cin >> name;— stops at space. Full line:getline(cin, line); - Print:
cout << name; - Concatenate:
s1 + s2ors1 += s2.
#include <iostream>
#include <string>
using namespace std;
int main() {
string first = "Learn";
string second = "Tech";
string full = first + " " + second;
cout << full << "\n";
cout << "Length = " << full.size() << "\n";
return 0;
} Differences between C-string and std::string
- Use
std::stringin new C++ code unless an API forces a C-string.
| Point | C-string (char[]) | std::string |
|---|---|---|
| Type | char name[50]; | string name; |
| Length | Fixed buffer; watch overflow | Grows as needed |
| Terminator | Needs '\0' | Managed for you |
| Join | strcat (unsafe if small buffer) | + / += / append |
| Compare | strcmp | == / compare |
| Header | | |
| I/O | cin >> / gets (avoid) | cin / getline |
std::string library functions (table)
- These are the most used **member functions** of
std::string. Call them ass.function(...). - Also related free helpers:
getline,to_string,stoi/stod(in).
| Function | What it does | Example | Typical result |
|---|---|---|---|
size() / length() | Number of characters | s.size() | 5 for "Hello" |
empty() | True if length is 0 | s.empty() | true / false |
clear() | Make string empty | s.clear() | s becomes "" |
at(i) / s[i] | Character at index i | s.at(0) | First char |
front() / back() | First / last character | s.back() | Last char |
+ / += | Concatenate | s += "!" | Append text |
append(str) | Append another string | s.append(" Guru") | Longer string |
push_back(ch) | Add one character at end | s.push_back('!') | One char added |
pop_back() | Remove last character | s.pop_back() | Shorter by 1 |
insert(pos, str) | Insert text at position | s.insert(0, "Hi ") | Text in the middle/start |
erase(pos, n) | Remove n chars from pos | s.erase(2, 3) | Those chars gone |
replace(pos, n, str) | Replace n chars with str | s.replace(0, 5, "Hey") | Segment replaced |
substr(pos, n) | Copy substring of length n | s.substr(0, 4) | New string piece |
find(str) | First index of str | s.find("Tech") | Index or npos |
rfind(str) | Last index of str | s.rfind("a") | Index or npos |
find_first_of(chars) | First index of any listed char | s.find_first_of("aeiou") | Vowel position |
compare(str) | Lexicographic compare | s.compare(t) | <0 / 0 / >0 |
== / != / < … | Relational operators | s == t | Boolean |
c_str() | C-string pointer (read-only) | s.c_str() | For C APIs |
data() | Pointer to characters | s.data() | Underlying buffer |
resize(n) | Change length to n | s.resize(10) | Pad/truncate |
reserve(n) | Reserve capacity (no must-grow) | s.reserve(100) | Fewer reallocations |
capacity() | Allocated storage size | s.capacity() | ≥ size() |
swap(other) | Swap two strings | s.swap(t) | Contents exchanged |
assign(str) | Replace entire content | s.assign("New") | s becomes "New" |
copy(buf, n, pos) | Copy into char buffer | s.copy(buf, 3) | Chars copied |
Related <string> / conversion helpers
- These are free functions commonly used with strings (not all are members of
string).
| Function | Purpose | Example |
|---|---|---|
getline(cin, s) | Read a full line (keeps spaces) | getline(cin, name); |
to_string(num) | Number → string | to_string(42) → "42" |
stoi(s) | String → int | stoi("123") → 123 |
stol(s) / stoll(s) | String → long / long long | stoll("999999") |
stof(s) / stod(s) | String → float / double | stod("3.14") |
getline + stringstream | Split words / parse fields | CSV-style parsing |
Useful <cstring> functions (C-strings)
- Use when working with
char[]/const char*. Preferstd::stringwhen you control the type. - Always ensure the destination buffer is large enough for
strcpy/strcat.
| Function | Purpose | Notes |
|---|---|---|
strlen(s) | Length without '\0' | Does not count terminator |
strcpy(dest, src) | Copy string | Buffer overflow risk |
strncpy(dest, src, n) | Copy up to n chars | May omit '\0' — be careful |
strcat(dest, src) | Concatenate onto dest | Needs enough space |
strcmp(a, b) | Compare | 0 if equal |
strncmp(a, b, n) | Compare first n chars | Safer prefix check |
strchr(s, ch) | Find character | Returns pointer or null |
strstr(s, sub) | Find substring | Returns pointer or null |
Real-life string examples
- **Login:** check
username/passwordlength and compare with stored values. - **Email:** find
@withfind, take domain withsubstr. - **Full name:** join first +
" "+ last with+orappend. - **OTP / PIN:** fixed short string; validate every character is a digit.
- **File path:** find last
'/'or'\\'withrfind, thensubstrfor the file name. - **Search box:**
findwhether a keyword appears in a product title (case rules matter).
string email = "student@learntechguru.com";
auto at = email.find('@');
if (at != string::npos) {
string user = email.substr(0, at);
string domain = email.substr(at + 1);
cout << user << " / " << domain << "\n";
} Indexing and looping over characters
- Valid indices:
0tos.size() - 1. - Range-for is clearest for read-only walks:
for (char ch : s). - Use
const char&/char&when you need references; prefer range-for over manual index unless you need the index.
string s = "C++";
for (size_t i = 0; i < s.size(); i++) cout << s[i] << " ";
cout << "\n";
for (char ch : s) cout << ch; Advanced — Strings
find, npos, and substr patterns
findreturnsstring::nposwhen not found — always check before using the index.substr(pos)takes fromposto the end;substr(pos, n)takes up toncharacters.- Chaining find + substr is the usual “parse email / path / CSV field” pattern.
find(sub, startPos)continues searching from an offset — useful for counting occurrences.
string s = "one,two,three";
size_t start = 0, comma;
while ((comma = s.find(',', start)) != string::npos) {
cout << s.substr(start, comma - start) << "\n";
start = comma + 1;
}
cout << s.substr(start) << "\n"; // last field Capacity, SSO, and performance notes
size()is length;capacity()is allocated storage — capacity may be larger than size.- Many implementations use **SSO** (small string optimization): short strings stay on the stack.
reserve(n)before many appends can reduce reallocations.- Prefer
+=/appendin a loop over repeateds = s + xfor large builds (fewer temporaries). - Passing
const string&avoids copies; returning by value is fine (move/RVO).
string_view (C++17)
string_viewis a **non-owning** view: pointer + length — great for read-only APIs.- Do **not** keep a
string_viewafter the underlying string dies (dangling). - Useful to accept both
stringand string literals without forcing a copy intostring.
#include <string_view>
using namespace std;
size_t len(string_view sv) { return sv.size(); }
// len("hello"); len(string("hi")); Compare, sort order, and case
==checks equality;</compareuse lexicographic (dictionary) order by character codes.- Uppercase letters usually sort before lowercase in ASCII (
'A'<'a'). - Case-insensitive compare is not built-in — normalize with a loop or algorithm, or use a library.
comparereturns 0 if equal, negative if*thisis less, positive if greater.
string a = "Apple", b = "Banana";
if (a < b) cout << "Apple comes first\n";
cout << a.compare(b) << "\n"; // negative Real-life advanced models
- URL path segments: split on
'/'with repeatedfind. - Mask a card number: keep last 4 chars, replace the rest with
*. - Slug for a blog title: replace spaces with
-, erase punctuation. - Validate password: length, and
find_first_offor digits / special characters.
Tricky Interview Points
Q1) What is std::string in C++?
Answer A standard library class that manages a dynamic sequence of characters with operations like size, append, find, and substr. Prefer it over raw char arrays for most application text.
Q2) Difference between C-string and std::string?
Answer A C-string is a char array ending with '\0' and fixed/manual sizing. std::string manages length and memory and provides rich member functions and operators.
Q3) Difference between size() and capacity()?
Answer size()/length() is how many characters are currently stored. capacity() is how much storage is allocated and may be larger than size().
Q4) What does find return when the substring is missing?
Answer string::npos (a special size_t value). Always check for npos before using the returned index.
Q5) How do you read a full line with spaces?
Answer Use getline(cin, s); — cin >> s stops at the first whitespace.
Q6) What does substr(pos, n) do?
Answer Returns a new string with up to n characters starting at index pos. If n is omitted, it takes from pos to the end.
Q7) How do you convert string to int and int to string?
Answer stoi("123") converts to int; to_string(123) converts to string. Also stol/stoll/stod for other types.
Q8) What is c_str() used for?
Answer It returns a const char* to a null-terminated C-string view of the content, typically for C APIs that need const char*.
Q9) What is string_view?
Answer A non-owning read-only view of a character sequence (C++17). Do not use it after the underlying string is destroyed.
Q10) Name important std::string functions.
Answer size/length, empty, clear, append, insert, erase, replace, substr, find/rfind, compare, c_str, push_back/pop_back, at/[].
Q11) Are string indices 0-based?
Answer Yes. Valid indices are 0 through size()-1. Out-of-range at(i) throws; operator[] does not bounds-check.
Q12) Give a real-life use of find and substr.
Answer Parsing an email: find('@'), then substr for username and domain.
Simple Programs
Create, append, and print length
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Learn";
s += " Tech";
s.append(" Guru");
cout << s << "\nLength = " << s.size() << "\n";
return 0;
} getline — full name with spaces
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "Full name: ";
getline(cin, name);
cout << "Hello, " << name << "!\n";
return 0;
} find + substr — parse email
#include <iostream>
#include <string>
using namespace std;
int main() {
string email = " intern@learntechguru.com ";
// trim spaces simply for demo:
while (!email.empty() && email.front() == ' ') email.erase(0, 1);
while (!email.empty() && email.back() == ' ') email.pop_back();
auto at = email.find('@');
if (at == string::npos) {
cout << "Invalid email\n";
return 0;
}
cout << "User: " << email.substr(0, at) << "\n";
cout << "Domain: " << email.substr(at + 1) << "\n";
return 0;
} insert / erase / replace
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello World";
s.insert(5, ",");
cout << s << "\n";
s.erase(5, 1);
cout << s << "\n";
s.replace(6, 5, "C++");
cout << s << "\n";
return 0;
} Count vowels with indexing
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string s = "Education";
int vowels = 0;
for (char ch : s) {
char c = static_cast<char>(tolower(static_cast<unsigned char>(ch)));
if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u') vowels++;
}
cout << "Vowels = " << vowels << "\n";
return 0;
} stoi / to_string conversion
#include <iostream>
#include <string>
using namespace std;
int main() {
string priceText = "499";
int price = stoi(priceText);
int total = price * 2;
cout << "Total = " << to_string(total) << "\n";
return 0;
} Password checks with library functions
#include <iostream>
#include <string>
using namespace std;
int main() {
string pass = "Abcd@123";
bool okLen = pass.size() >= 8;
bool hasDigit = pass.find_first_of("0123456789") != string::npos;
bool hasSpecial = pass.find_first_of("@#$%&*") != string::npos;
cout << (okLen && hasDigit && hasSpecial ? "Strong\n" : "Weak\n");
return 0;
} Problem Solving Tricks
- Prefer std::string over char[] for application text.
- Use getline for lines with spaces; cin >> for single tokens.
- Always check find(...) != string::npos before using the index.
- size() and length() are the same for std::string.
- at(i) bounds-checks and throws; s[i] does not.
- Build large strings with += / append; avoid s = s + x in tight loops when possible.
- c_str() when a C API needs const char*.
- to_string / stoi for number ↔ text conversions.
- Keep a cheat-sheet of append, insert, erase, replace, substr, find.
- string_view is non-owning — never outlive the source string.
- For case-insensitive work, normalize characters explicitly.
- Partial init mind-set: empty() before assuming content exists.
Practice Programs List
- Read a full name with getline and print “Hello,
”. - Concatenate first and last name with a space; print size().
- Use find and substr to split an email into user and domain.
- Count vowels and consonants in a string.
- Check if a string is a palindrome (ignore case as a bonus).
- Replace all spaces with hyphens using a loop + replace or rebuild.
- Validate a password: length ≥ 8, at least one digit and one special char.
- Parse "name,age,city" CSV with repeated find on commas.
- Convert "2026" with stoi, add 1, print with to_string.
- Use insert to add a title "Mr. " at the start of a name.
- Use rfind to extract a file name from a path string.
- Write a function bool contains(const string& hay, const string& needle) using find.
- Compare two product codes with == and with compare().
- Build a sentence from words in an array of string using append.