Week 8
Week 8
Arrays and strings are fundamental data structures in C++ used for storing and
managing sequences of data. This section covers single-dimensional and multi-
dimensional arrays, string handling, pointers and arrays, character arrays, and the
std::string class.
Syntax:
Example:
Accessing Elements: You can access array elements using the index, starting
from 0.
Syntax:
A character array is an array of characters terminated by a null character (\0), which marks the
end of the string.
Syntax:
Example:
Or using string
literals:
Common Operations:
Example:
2.2.
std::string Class
The
std::string class from
the Standard Library provides a more flexible and powerful way to handle strings in C++. It
automatically manages memory and offers various member functions for string manipulation.
Example:
Common std::string Operations:
3. Pointers and
Arrays
In C++, arrays and pointers are closely related. An array's name is a constant pointer to its first
element, and pointers can be used to traverse through the array.
The array's name acts as a pointer to the first element of the array.
Example:
Pointer
Arithmetic with Arrays:
Example:
Dynamic Arrays Using Pointers:
You can dynamically allocate arrays at runtime using pointers and the new keyword.
Example:
A character array is an array of characters terminated by a null character ( \0). They are less
flexible than std::string, but still widely used in C-style programming.
Example:
Comparison:
Conclusion