Arrays and strings are essential components of C++ for storing and manipulating collections of data. Arrays allow us to store multiple elements of the same type, while strings enable easy handling of text. This section covers single-dimensional and multi-dimensional arrays, basic array operations, an introduction to C-style strings and std::string
, and some commonly used string manipulation functions.
Single-Dimensional Arrays
A single-dimensional array is a collection of elements of the same type arranged in a linear order.
Syntax:
scores
is a single-dimensional array containing five integer values. We use a loop to access and print each element.Multi-Dimensional Arrays
Multi-dimensional arrays, like two-dimensional arrays, are arrays of arrays. They are useful for storing tabular data or matrices.
Syntax:
matrix
is a 2D array with 2 rows and 3 columns, holding six integers in a tabular format.Array Operations
Common operations on arrays include accessing elements, updating values, and iterating over elements.
Example: Basic array operations.
numbers
and then calculate the sum of all elements.Introduction to C-Strings and std::string
C-Strings
C-strings are arrays of characters terminated by a null character ('\0'
). They are the traditional way of handling strings in C++.
Syntax:
Here, greeting
is a C-string that initially contains "Hello"
and is later modified to "Hello World"
using strcat
.
std::string
std::string
is the C++ standard string class that provides powerful features for handling and manipulating strings. Unlike C-strings, std::string
is safer and easier to work with.
Example: Using std::string
.
std::string
variable message
and append " World"
to it using +=
. We also find the substring "World"
using the find
function.String Manipulation Functions
Here are some common functions for manipulating strings in C++:
strcpy(dest, src)
: Copiessrc
C-string todest
.strlen(str)
: Returns the length of a C-string.strcat(dest, src)
: Concatenatessrc
C-string to the end ofdest
.std::string::append()
: Appends to astd::string
.std::string::find()
: Searches for a substring in astd::string
.
Example: Common string functions.
strcpy
copies a C-string, and strlen
gives its length. The std::string
class append
method is used to add " C++ World"
to text
, and find
locates the substring "C++"
.