Ugenz Academy/Tutorial

String

19 min read3,625 words

Reading progress

Keep learning

C++ Strings

1. Introduction

A string is a sequence of characters used to represent text.

Examples of strings are:

"Hello" "Anuradha" "Welcome to C++" "Computer Science"

In C++, strings can be handled mainly in two ways:

  1. C-style strings using character arrays
  2. C++ strings using the std::string class

The std::string class is generally easier and safer to use for normal string operations.

2. Why Use Strings?

Strings are used to store text such as:

  • Student names
  • Addresses
  • Phone numbers
  • Email addresses
  • Messages
  • Passwords
  • Product names
  • City names
  • Sentences

Example

string name = "Anuradha";

3. Including the String Library

To use std::string, include the <string> header.

#include <string>

Example

#include <iostream> #include <string> using namespace std; int main() { string name = "Anuradha"; cout << name; return 0; }

Output

Anuradha

4. Declaring a String

The basic syntax is:

string variable_name;

Example

string name;

This creates an empty string.

We can assign a value later:

name = "Anuradha";

5. Initializing a String

A string can be initialized when it is declared.

Example

string name = "Anuradha";

Another example:

string city = "Janakpur";

Complete Program

#include <iostream> #include <string> using namespace std; int main() { string name = "Anuradha"; string city = "Janakpur"; cout << "Name: " << name << endl; cout << "City: " << city; return 0; }

Output

Name: Anuradha City: Janakpur

6. Taking String Input Using cin

We can use cin to take a string from the user.

Example

#include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter your name: "; cin >> name; cout << "Your name is: " << name; return 0; }

Example Input

Anuradha

Output

Your name is: Anuradha

7. Problem with cin

cin stops reading when it encounters whitespace.

For example, if the user enters:

Anuradha Mandal

then:

cin >> name;

will read only:

Anuradha

To read an entire line including spaces, use getline().

8. Taking Full Line Input Using getline()

The getline() function reads an entire line of text.

Syntax

getline(cin, variable);

Example

#include <iostream> #include <string> using namespace std; int main() { string fullName; cout << "Enter your full name: "; getline(cin, fullName); cout << "Full Name: " << fullName; return 0; }

Example Input

Anuradha Mandal

Output

Full Name: Anuradha Mandal

9. cin and getline() Together

When cin is used before getline(), the newline left in the input buffer can cause getline() to read an empty line.

Problem

int age; string name; cin >> age; getline(cin, name);

The getline() may immediately read the leftover newline.

Solution

Use cin.ignore().

Example

#include <iostream> #include <string> using namespace std; int main() { int age; string name; cout << "Enter age: "; cin >> age; cin.ignore(); cout << "Enter full name: "; getline(cin, name); cout << "Name: " << name << endl; cout << "Age: " << age; return 0; }

Example Input

20 Anuradha Mandal

Output

Name: Anuradha Mandal Age: 20

10. Finding String Length

The .length() function returns the number of characters in a string.

Example

#include <iostream> #include <string> using namespace std; int main() { string name = "Anuradha"; cout << "Length = " << name.length(); return 0; }

Output

Length = 8

The .size() function can also be used:

cout << name.size();

For std::string, .length() and .size() return the same number of characters.

11. Accessing Individual Characters

We can access individual characters using an index.

Like arrays, string indexing starts from 0.

Example

#include <iostream> #include <string> using namespace std; int main() { string name = "Anuradha"; cout << name[0] << endl; cout << name[1] << endl; cout << name[2] << endl; return 0; }

Output

A n u

Index Representation

Index: 0 1 2 3 4 5 6 7 ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ String: A n u r a d h a

12. Changing a Character

Individual characters can be changed using their index.

Example

#include <iostream> #include <string> using namespace std; int main() { string name = "Anuradha"; name[0] = 'X'; cout << name; return 0; }

Output

Xnuradha

13. Accessing Characters Using .at()

The .at() function can also be used to access a character.

Example

#include <iostream> #include <string> using namespace std; int main() { string name = "Anuradha"; cout << name.at(0); return 0; }

Output

A

One benefit of .at() is that it performs bounds checking and can throw an exception if the index is invalid.

14. Concatenating Strings

Concatenation means joining two or more strings together.

The + operator can be used.

Example

#include <iostream> #include <string> using namespace std; int main() { string firstName = "Anuradha"; string lastName = "Mandal"; string fullName = firstName + " " + lastName; cout << fullName; return 0; }

Output

Anuradha Mandal

15. Using append()

The append() function can also join strings.

Example

#include <iostream> #include <string> using namespace std; int main() { string first = "Hello "; string second = "World"; first.append(second); cout << first; return 0; }

Output

Hello World

16. Comparing Strings

Strings can be compared using operators such as:

== != < > <= >=

Example

#include <iostream> #include <string> using namespace std; int main() { string a = "apple"; string b = "apple"; if (a == b) { cout << "Strings are equal"; } return 0; }

Output

Strings are equal

17. Comparing Different Strings

Example

#include <iostream> #include <string> using namespace std; int main() { string a = "Hello"; string b = "World"; if (a == b) { cout << "Equal"; } else { cout << "Not Equal"; } return 0; }

Output

Not Equal

18. Using compare()

The compare() function can compare two strings.

Example

#include <iostream> #include <string> using namespace std; int main() { string a = "Apple"; string b = "Apple"; if (a.compare(b) == 0) { cout << "Strings are equal"; } return 0; }

Output

Strings are equal

Generally:

compare() == 0 → Equal compare() < 0 → First string compares before second compare() > 0 → First string compares after second

19. Finding a Substring

The .find() function searches for a substring.

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "I love C++ programming"; size_t position = text.find("C++"); if (position != string::npos) { cout << "C++ found at index " << position; } return 0; }

Output

C++ found at index 7

string::npos means that the requested substring was not found.

20. Extracting a Substring

The .substr() function extracts part of a string.

Syntax

string.substr(start, length);

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "Hello World"; string result = text.substr(0, 5); cout << result; return 0; }

Output

Hello

Here:

text.substr(0, 5)

means:

  • Start at index 0
  • Extract 5 characters

21. Inserting into a String

The .insert() function adds characters or another string at a specified position.

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "Hello World"; text.insert(6, "C++ "); cout << text; return 0; }

Output

Hello C++ World

22. Erasing Characters

The .erase() function removes characters.

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "Hello World"; text.erase(5, 1); cout << text; return 0; }

Output

HelloWorld

Here:

text.erase(5, 1);

means:

  • Start at index 5
  • Remove 1 character

23. Replacing Part of a String

The .replace() function replaces part of a string.

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "I like Java"; text.replace(7, 4, "C++"); cout << text; return 0; }

Output

I like C++

24. Checking Whether a String Is Empty

The .empty() function checks whether a string contains no characters.

Example

#include <iostream> #include <string> using namespace std; int main() { string name; if (name.empty()) { cout << "String is empty"; } return 0; }

Output

String is empty

25. Clearing a String

The .clear() function removes all characters from a string.

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "Hello World"; text.clear(); cout << "Length = " << text.length(); return 0; }

Output

Length = 0

26. Adding Characters Using push_back()

The push_back() function adds one character to the end of a string.

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "Hello"; text.push_back('!'); cout << text; return 0; }

Output

Hello!

27. Removing the Last Character

The pop_back() function removes the last character.

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "Hello!"; text.pop_back(); cout << text; return 0; }

Output

Hello

28. First and Last Character

The .front() function returns the first character.

The .back() function returns the last character.

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "Hello"; cout << "First = " << text.front() << endl; cout << "Last = " << text.back(); return 0; }

Output

First = H Last = o

29. Loop Through a String

A for loop can be used to access every character.

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "Hello"; for (int i = 0; i < text.length(); i++) { cout << text[i] << endl; } return 0; }

Output

H e l l o

30. Range-Based Loop with String

A range-based for loop provides a simple way to process each character.

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "Hello"; for (char ch : text) { cout << ch << " "; } return 0; }

Output

H e l l o

31. Counting Characters

We can use a loop to count specific characters.

Example: Count Vowels

#include <iostream> #include <string> using namespace std; int main() { string text = "education"; int count = 0; for (char ch : text) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { count++; } } cout << "Number of vowels = " << count; return 0; }

Output

Number of vowels = 5

32. Reversing a String

A string can be displayed in reverse order using a loop.

Example

#include <iostream> #include <string> using namespace std; int main() { string text = "Hello"; cout << "Reverse = "; for (int i = text.length() - 1; i >= 0; i--) { cout << text[i]; } return 0; }

Output

Reverse = olleH

33. Checking Palindrome

A palindrome is a word or sequence that reads the same forward and backward.

Examples:

madam level radar

Example

#include <iostream> #include <string> using namespace std; int main() { string text; cout << "Enter a word: "; cin >> text; bool palindrome = true; int left = 0; int right = text.length() - 1; while (left < right) { if (text[left] != text[right]) { palindrome = false; break; } left++; right--; } if (palindrome) { cout << "Palindrome"; } else { cout << "Not a palindrome"; } return 0; }

Example Input

madam

Output

Palindrome

34. Converting String to Number

The <string> library provides functions such as stoi() and stod().

String to Integer

#include <iostream> #include <string> using namespace std; int main() { string text = "123"; int number = stoi(text); cout << number + 10; return 0; }

Output

133

String to Double

string text = "25.5"; double number = stod(text);

35. Converting Number to String

The to_string() function converts a numeric value into a string.

Example

#include <iostream> #include <string> using namespace std; int main() { int age = 20; string text = "Age: " + to_string(age); cout << text; return 0; }

Output

Age: 20

36. C-Style Strings

Before std::string, text was commonly stored using character arrays.

A C-style string is a character array terminated by the null character:

'\0'

Example

char name[] = "Anuradha";

Conceptually:

A n u r a d h a \0

The '\0' indicates the end of the C-style string.

37. C-Style String Example

#include <iostream> using namespace std; int main() { char name[] = "Anuradha"; cout << name; return 0; }

Output

Anuradha

38. C-Style String Functions

C-style strings commonly use functions from <cstring>.

Some important functions are:

FunctionPurpose
strlen()Finds length
strcpy()Copies a string
strcat()Concatenates strings
strcmp()Compares strings

Example of strlen()

#include <iostream> #include <cstring> using namespace std; int main() { char name[] = "Anuradha"; cout << strlen(name); return 0; }

Output

8

For ordinary C++ programming, std::string is generally more convenient than manually managing character arrays.

39. Array of Strings

We can store multiple strings in an array.

Example

#include <iostream> #include <string> using namespace std; int main() { string names[3] = { "Anuradha", "Ram", "Sita" }; for (int i = 0; i < 3; i++) { cout << names[i] << endl; } return 0; }

Output

Anuradha Ram Sita

40. String with User Details

Strings are commonly used when creating student or user information programs.

Example

#include <iostream> #include <string> using namespace std; int main() { string name; string address; string email; cout << "Enter your name: "; getline(cin, name); cout << "Enter your address: "; getline(cin, address); cout << "Enter your email: "; getline(cin, email); cout << "\nStudent Details" << endl; cout << "Name: " << name << endl; cout << "Address: " << address << endl; cout << "Email: " << email << endl; return 0; }

Example Input

Anuradha Mandal Janakpur anuradha@example.com

Output

Student Details Name: Anuradha Mandal Address: Janakpur Email: anuradha@example.com

41. Passing a String to a Function

A string can be passed to a function.

Example

#include <iostream> #include <string> using namespace std; void display(string name) { cout << "Hello " << name; } int main() { display("Anuradha"); return 0; }

Output

Hello Anuradha

42. Passing String by Reference

A string can be passed by reference to avoid making an unnecessary copy when the function does not need to modify it.

Example

#include <iostream> #include <string> using namespace std; void display(const string &name) { cout << "Name: " << name; } int main() { string name = "Anuradha"; display(name); return 0; }

Output

Name: Anuradha

Here:

const string &name

means the function receives a reference and does not modify the original string.

43. Complete String Program

The following program takes a student's full name and address and displays useful information.

#include <iostream> #include <string> using namespace std; int main() { string name; string address; cout << "Enter your full name: "; getline(cin, name); cout << "Enter your address: "; getline(cin, address); cout << "\n--- Student Information ---" << endl; cout << "Name: " << name << endl; cout << "Address: " << address << endl; cout << "Name Length: " << name.length() << endl; if (!name.empty()) { cout << "First Character: " << name.front() << endl; cout << "Last Character: " << name.back() << endl; } return 0; }

Example Input

Anuradha Mandal Janakpur

Output

--- Student Information Name: Anuradha Mandal Address: Janakpur Name Length: 15 First Character: A Last Character: l

44. Common String Functions

FunctionDescriptionExample
length()Returns string lengthname.length()
size()Returns string lengthname.size()
empty()Checks whether string is emptyname.empty()
at()Accesses character with bounds checkingname.at(0)
front()Returns first charactername.front()
back()Returns last charactername.back()
append()Adds another stringa.append(b)
find()Searches for texttext.find("C++")
substr()Extracts part of a stringtext.substr(0, 5)
insert()Inserts texttext.insert(2, "Hi")
erase()Removes characterstext.erase(2, 3)
replace()Replaces characterstext.replace(0, 3, "Hi")
clear()Removes all characterstext.clear()
push_back()Adds one charactertext.push_back('!')
pop_back()Removes last charactertext.pop_back()

45. Difference Between std::string and C-Style String

std::stringC-Style String
Uses std::stringUses char array
Header: <string>Header: <cstring> for many functions
Easier to useRequires more manual management
Dynamic sizeFixed array storage
Provides many member functionsUses library functions
Example: string nameExample: char name[20]
No need to manually add '\0' when assigning normal string literalsRequires null termination for proper C-string behavior

46. String vs Character

A character stores one character.

A string stores a sequence of characters.

Character

char grade = 'A';

String

string name = "Anuradha";

Difference

CharacterString
Stores one characterStores multiple characters
Uses single quotesUses double quotes
Example: 'A'Example: "Anuradha"
Data type: charData type: string

47. Common String Errors

Error 1: Using Single Quotes for a String

Incorrect:

string name = 'Anuradha';

Correct:

string name = "Anuradha";

Single quotes are normally used for character literals:

char grade = 'A';

Error 2: Forgetting the Header

If using std::string, include:

#include <string>

Error 3: Using cin for a Full Name

cin >> name;

This reads only up to whitespace.

For a full name:

getline(cin, name);

Error 4: Invalid Index

For:

string name = "Anu";

valid indexes are:

0, 1, 2

Using an invalid index can cause undefined behavior when using operator[].

48. Advantages of std::string

  • Easy to use
  • Supports dynamic length
  • Provides many useful functions
  • Easy concatenation
  • Easy comparison
  • Easy searching
  • Easy substring extraction
  • Easier than C-style character arrays
  • Works well with standard C++ libraries

49. Disadvantages of Strings

  • String operations can use more memory than a single character.
  • Very large or frequent string operations can affect performance.
  • Incorrect indexing can cause errors or undefined behavior.
  • Converting between C-style strings and std::string requires care.

50. Important String Rules

  1. Use double quotes for string literals.
  2. Use single quotes for character literals.
  3. Include <string> when using std::string.
  4. String indexing starts from 0.
  5. Use getline() to read spaces.
  6. Use .length() or .size() to find length.
  7. Use + or .append() to concatenate strings.
  8. Use .find() to search for text.
  9. Use .substr() to extract part of a string.
  10. Use .empty() to check whether a string is empty.
  11. Use .clear() to remove all characters.
  12. C-style strings end with a null character '\0'.
  13. Use std::string for most normal C++ string handling.

51. Summary

String ↓ std::string ↓ Declaration ↓ Initialization ↓ Input using cin / getline() ↓ Access using index ↓ length() ↓ Concatenation ↓ Comparison ↓ Search ↓ Substring ↓ Insert / Erase / Replace

52. Conclusion

Strings are essential in C++ because most real-world programs need to work with text.

The most important concepts are:

  • std::string
  • getline()
  • String indexing
  • length() and size()
  • String concatenation
  • String comparison
  • find()
  • substr()
  • insert()
  • erase()
  • replace()
  • push_back() and pop_back()
  • C-style strings

For modern C++ programs, std::string is generally the preferred choice for ordinary text processing because it provides convenient operations and manages its storage automatically.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy