Skip to main content

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.

L1

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 char arrays 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.
IdeaMeaningReal-life mapping
CharactersLetters / digits / symbolsLetters in a name
LengthHow many charactersPassword must be ≥ 8
IndexPosition from 0First letter of a name
Empty string"" — length 0Blank form field

Creating and using std::string

  • Declare: string name; or string name = "Ravi";
  • Read a word: cin >> name; — stops at space. Full line: getline(cin, line);
  • Print: cout << name;
  • Concatenate: s1 + s2 or s1 += 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::string in new C++ code unless an API forces a C-string.
PointC-string (char[])std::string
Typechar name[50];string name;
LengthFixed buffer; watch overflowGrows as needed
TerminatorNeeds '\0'Managed for you
Joinstrcat (unsafe if small buffer)+ / += / append
Comparestrcmp== / compare
Header
I/Ocin >> / gets (avoid)cin / getline

std::string library functions (table)

  • These are the most used **member functions** of std::string. Call them as s.function(...).
  • Also related free helpers: getline, to_string, stoi / stod (in ).
FunctionWhat it doesExampleTypical result
size() / length()Number of characterss.size()5 for "Hello"
empty()True if length is 0s.empty()true / false
clear()Make string emptys.clear()s becomes ""
at(i) / s[i]Character at index is.at(0)First char
front() / back()First / last characters.back()Last char
+ / +=Concatenates += "!"Append text
append(str)Append another strings.append(" Guru")Longer string
push_back(ch)Add one character at ends.push_back('!')One char added
pop_back()Remove last characters.pop_back()Shorter by 1
insert(pos, str)Insert text at positions.insert(0, "Hi ")Text in the middle/start
erase(pos, n)Remove n chars from poss.erase(2, 3)Those chars gone
replace(pos, n, str)Replace n chars with strs.replace(0, 5, "Hey")Segment replaced
substr(pos, n)Copy substring of length ns.substr(0, 4)New string piece
find(str)First index of strs.find("Tech")Index or npos
rfind(str)Last index of strs.rfind("a")Index or npos
find_first_of(chars)First index of any listed chars.find_first_of("aeiou")Vowel position
compare(str)Lexicographic compares.compare(t)<0 / 0 / >0
== / != / < …Relational operatorss == tBoolean
c_str()C-string pointer (read-only)s.c_str()For C APIs
data()Pointer to characterss.data()Underlying buffer
resize(n)Change length to ns.resize(10)Pad/truncate
reserve(n)Reserve capacity (no must-grow)s.reserve(100)Fewer reallocations
capacity()Allocated storage sizes.capacity()≥ size()
swap(other)Swap two stringss.swap(t)Contents exchanged
assign(str)Replace entire contents.assign("New")s becomes "New"
copy(buf, n, pos)Copy into char buffers.copy(buf, 3)Chars copied

Related <string> / conversion helpers

  • These are free functions commonly used with strings (not all are members of string).
FunctionPurposeExample
getline(cin, s)Read a full line (keeps spaces)getline(cin, name);
to_string(num)Number → stringto_string(42) → "42"
stoi(s)String → intstoi("123") → 123
stol(s) / stoll(s)String → long / long longstoll("999999")
stof(s) / stod(s)String → float / doublestod("3.14")
getline + stringstreamSplit words / parse fieldsCSV-style parsing

Useful <cstring> functions (C-strings)

  • Use when working with char[] / const char*. Prefer std::string when you control the type.
  • Always ensure the destination buffer is large enough for strcpy / strcat.
FunctionPurposeNotes
strlen(s)Length without '\0'Does not count terminator
strcpy(dest, src)Copy stringBuffer overflow risk
strncpy(dest, src, n)Copy up to n charsMay omit '\0' — be careful
strcat(dest, src)Concatenate onto destNeeds enough space
strcmp(a, b)Compare0 if equal
strncmp(a, b, n)Compare first n charsSafer prefix check
strchr(s, ch)Find characterReturns pointer or null
strstr(s, sub)Find substringReturns pointer or null

Real-life string examples

  • **Login:** check username / password length and compare with stored values.
  • **Email:** find @ with find, take domain with substr.
  • **Full name:** join first + " " + last with + or append.
  • **OTP / PIN:** fixed short string; validate every character is a digit.
  • **File path:** find last '/' or '\\' with rfind, then substr for the file name.
  • **Search box:** find whether 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: 0 to s.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;
L2

Advanced — Strings

find, npos, and substr patterns

  • find returns string::npos when not found — always check before using the index.
  • substr(pos) takes from pos to the end; substr(pos, n) takes up to n characters.
  • 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 += / append in a loop over repeated s = s + x for large builds (fewer temporaries).
  • Passing const string& avoids copies; returning by value is fine (move/RVO).

string_view (C++17)

  • string_view is a **non-owning** view: pointer + length — great for read-only APIs.
  • Do **not** keep a string_view after the underlying string dies (dangling).
  • Useful to accept both string and string literals without forcing a copy into string.
#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; < / compare use 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.
  • compare returns 0 if equal, negative if *this is 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 repeated find.
  • 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_of for digits / special characters.
L3

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.

L4

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;
}
L5

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.
L6

Practice Programs List

  1. Read a full name with getline and print “Hello, ”.
  2. Concatenate first and last name with a space; print size().
  3. Use find and substr to split an email into user and domain.
  4. Count vowels and consonants in a string.
  5. Check if a string is a palindrome (ignore case as a bonus).
  6. Replace all spaces with hyphens using a loop + replace or rebuild.
  7. Validate a password: length ≥ 8, at least one digit and one special char.
  8. Parse "name,age,city" CSV with repeated find on commas.
  9. Convert "2026" with stoi, add 1, print with to_string.
  10. Use insert to add a title "Mr. " at the start of a name.
  11. Use rfind to extract a file name from a path string.
  12. Write a function bool contains(const string& hay, const string& needle) using find.
  13. Compare two product codes with == and with compare().
  14. Build a sentence from words in an array of string using append.