Back to C++
2026-02-216 min read

Access Strings (C++)

Learn Access Strings (C++) step by step with clear examples and exercises.

Title: Accessing Strings in C++: A full guide

Why This Matters

In this tutorial, we will delve into accessing strings in C++, a crucial skill for any programmer. Understanding how to manipulate strings is essential for creating user-friendly interfaces, parsing input from files, and interacting with APIs. Additionally, being able to effectively work with strings can help you solve real-world programming problems and stand out during interviews.

Prerequisites

Before diving into accessing strings in C++, it's important that you have a solid understanding of the following concepts:

  • Variables and data types
  • Basic input/output operations (cin, cout)
  • Arrays
  • Operators (arithmetic, relational, logical)
  • Control structures (if-else, loops)
  • Pointers (optional but recommended for C-style strings)
  • Functions and function overloading
  • Namespaces

Core Concept

In C++, a string is an array of characters terminated by a null character ('\0'). The Standard Template Library (STL) provides the string class to simplify working with strings. However, it's also possible to use C-style strings (arrays of characters).

C-Style Strings

C-style strings are arrays of characters that end with a null character ('\0'). To declare a C-style string, simply allocate memory for an array of characters and assign the string to it.

char myString[20] = "Hello World!";

To access individual characters in a C-style string, use indexing like any other array:

cout << myString[0]; // Outputs 'H'

Note that that the length of a C-style string can be obtained by finding the index of the null character.

int length = 0;
while (myString[length] != '\0') {
++length;
}
cout << "Length: " << length << endl; // Outputs '12'

Pointers and C-style Strings

Using pointers can make working with C-style strings more efficient. To declare a pointer to a character, use the following syntax:

char *myStringPtr = "Hello World!";

Now you can access individual characters using the pointer:

cout << *(myStringPtr); // Outputs 'H'

Dynamic Memory Allocation for C-style Strings

If you don't know the exact length of a string, you can use dynamic memory allocation to create an array of characters and store the string in it.

char *myString = new char[length + 1];
strcpy(myString, "Hello World!"); // Copies the string into the allocated memory

Remember to free the memory once you're done:

delete[] myString;

STL string Class

The string class in the STL provides a more convenient and efficient way to work with strings. To include it, add the following line at the top of your code:

#include <string>

To declare an STL string, use the following syntax:

std::string myString = "Hello World!";

Accessing individual characters in an STL string is as simple as using indexing:

cout << myString[0]; // Outputs 'H'

The length of an STL string can be obtained using the length() function:

cout << "Length: " << myString.length(); // Outputs '12'

String Concatenation

To concatenate two C-style strings, use the strcat() function from the string.h library:

#include <string.h>
char myString1[30] = "Hello ";
char myString2[30] = "World!";
strcat(myString1, myString2);
cout << myString1; // Outputs 'Hello World!'

For STL string, use the + operator:

std::string myString1 = "Hello ";
std::string myString2 = "World!";
myString1 += myString2;
cout << myString1; // Outputs 'Hello World!'

String Comparison

To compare two STL strings, use the == operator:

std::string str1 = "Hello";
std::string str2 = "World";
if (str1 == str2) {
cout << "The strings are equal." << endl;
} else {
cout << "The strings are not equal." << endl;
}

Worked Example

Let's create a simple program that takes a user's name as input, reverses it, and outputs the result.

#include <iostream>
#include <string>
#include <algorithm>

int main() {
std::string name;
std::reverse(name.begin(), name.end()); // Reverses the string in-place
cout << "Enter your name: ";
std::getline(std::cin, name);
cout << "Reversed Name: " << name << std::endl;
return 0;
}

Common Mistakes

  1. Forgetting to include the necessary libraries (string, string.h)
  2. Not allocating enough memory for C-style strings
  3. Indexing out of bounds in C-style strings
  4. Using strcat() with overlapping strings
  5. Failing to terminate C-style strings properly
  6. Not initializing the length variable when working with C-style strings
  7. Misusing the + operator with C-style strings
  8. Forgetting to include the null character at the end of a C-style string
  9. Using STL functions on C-style strings without converting them (e.g., using length() or comparing with ==)
  10. Failing to free dynamically allocated memory for C-style strings when finished

Subheadings under Common Mistakes:

  • Memory management issues with C-style strings
  • Mixing STL and C-style strings improperly

Practice Questions

  1. Write a program that takes two C-style strings as input and concatenates them, storing the result in an STL string.
  2. Create a program that counts the number of occurrences of a specific character in a given C-style string.
  3. Write a function that reverses an STL string.
  4. Implement a program that checks if two given C-style strings are anagrams (i.e., they contain the same characters).
  5. Create a program that finds all permutations of a given C-style string.
  6. Write a function that compares two C-style strings lexicographically (i.e., character by character, from left to right).
  7. Implement a program that removes duplicate characters from a given C-style string.
  8. Create a program that replaces all occurrences of a specific substring in an STL string.
  9. Write a function that finds the longest common subsequence between two C-style strings.
  10. Implement a program that checks if a given C-style string is a palindrome (i.e., reads the same forward and backward).

FAQ

What is the difference between C-style strings and STL string?

  • C-style strings are arrays of characters, while STL string is an object of the std::string class.

How do I find the length of a C-style string?

  • To find the length of a C-style string, iterate through the array until you reach the null character ('\0').

Can I use the + operator with C-style strings?

  • No, the + operator is not compatible with C-style strings. Instead, use strcat().

How do I concatenate two STL string objects?

  • To concatenate two STL string objects, use the += operator.

What happens if I don't include the necessary libraries (string, string.h)?

  • If you forget to include the necessary libraries, the compiler will not be able to find the functions or classes required for working with strings, resulting in errors.

How do I compare two STL strings lexicographically?

  • To compare two STL strings lexicographically, use the < operator.

What is the difference between a substring and a subsequence?

  • A substring is a contiguous sequence of characters within a string, while a subsequence can have gaps and does not need to be contiguous.

How do I find the longest common subsequence between two C-style strings?

  • To find the longest common subsequence between two C-style strings, use dynamic programming with a 2D array or recursion with memoization.

What is a palindrome and how can I check if a given C-style string is a palindrome?

  • A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward. To check if a given C-style string is a palindrome, you can use a recursive function or two pointers moving towards each other from both ends of the string.

How do I sort an STL vector containing strings lexicographically?

  • To sort an STL vector containing strings lexicographically, use the sort() function provided by the STL:
#include <algorithm>
std::vector<std::string> myVector = {"apple", "banana", "cherry"};
std::sort(myVector.begin(), myVector.end());
Access Strings (C++) | C++ | XQA Learn