Arrays and strings

array_and_string


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:

single_dimensional_array


Example: Declaring and initializing an array of integers.

single_array
In this example, 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:

multi_dimensional_array


Example: Declaring and initializing a 2D array (matrix).

multi_array
In this example, 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.

array_operations
In this example, we modify an element in 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:

string_syntax


Example: Basic C-string operations.

string

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.

string
In this example, we declare a 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): Copies src C-string to dest.
  • strlen(str): Returns the length of a C-string.
  • strcat(dest, src): Concatenates src C-string to the end of dest.
  • std::string::append(): Appends to a std::string.
  • std::string::find(): Searches for a substring in a std::string.

Example: Common string functions.

string_manipulation
In this code, 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++".

Post a Comment

Your comment will be visible after approval.
© TechTestLog. All rights reserved. Premium By Raushan Design
//My script