Intro to C++: Managing Arrays & Strings

What’s in an Array?

An array is a variable that can store multiple items of data unlike a regular variable that stores one pierce of data. Just like any variable, arrays must be declared before they can be accessed.

Initializing Arrays

You can initialize a simple array of built-in types, like integers (int) or characters (char), when you first declare the array. After the array name, put an equal sign and a list of comma separated values enclosed in the braces.

int nums[10] = { 0, 10, 20, 30, 40, 50, 60 ,70, 80, 90 }; 

This declared nums to be an array of 10 integers. Remember that the data are stored sequentially in array are elements that are numbered starting at zero. So nums[0] equals to 0, nums[1] equals to 10, and so on.

Arrays can be created for any data type but each element may only contain data of the same data type.

Inserting and Printing Elements

int mike[5] = {19, 10, 8, 17, 9}// change 4th element to 9
mike[3] = 9;
// take input from the user and insert in third element
cin >> mike[2];
// take input from the user and insert in (i+1)th element
cin >> mike[i];
// print first element of the array
cout << mike[0];
// print ith element of the array
cout >> mike[i-1];

Character Arrays

An array of characters can be used to store a string of text if the final elements contains the special \0 null character. For example:

char name[5] = {'p', 'n', 'o', 'p', '\0'};

Because this character-by-character approach is difficult to type and admits too many opportunities for error, C++ enables a shorthand form of string initialization using a literal:

char name[] = "pnop";

This form of initialization doesn’t require the null character; the compiler adds it automatically. The string β€œpnop” is 5 bytes including null.

Multidimensial Arrays

Collectively elements in an array is known as an index. Arrays can have more than one index. Arrays are suitable for data that consists of a known number of elements like a chessboard or coordinates which would be good examples in need of a two dimensional array.

For example:

int coordinates[2][3] = {{1,2,3} , {4,5,6}};

A three-dimensional array has three subscripts:

int cube[5,13,8];

Run the program below to see the output.

C-Style Character String

C++ supports a wide range of functions that can manipulate null-terminated strings. The header file <cstring> defines several functions to manipulate C strings and arrays.

╔═════════════════╦════════════════════════════════════════════╗
β•‘ Keyword β•‘ Functions and Purpose β•‘
╠═════════════════╬════════════════════════════════════════════╣
β•‘ strcpy(s1,s2) β•‘ copies string s2 into string s1. β•‘ ╠═════════════════╬════════════════════════════════════════════╣
β•‘ strcat(s1,s2) β•‘ concatenates string s2 onto the end of β•‘
β•‘ β•‘ string s1. β•‘
╠═════════════════╬════════════════════════════════════════════╣
β•‘ strlen(s1) β•‘ Returns the length of string s1; β•‘ ╠═════════════════╬════════════════════════════════════════════╣
β•‘ strcmp(s1,s2) β•‘ Returns 0 if s1 and s2 are the same; β•‘
β•‘ β•‘ less than 0 if s1<s2; greater than 0 if β•‘ β•‘ β•‘ if s1>s2. β•‘
╠═════════════════╬════════════════════════════════════════════╣
β•‘ strchr(s1,ch) β•‘ Returns a pointer to the first occurrence β•‘ β•‘ β•‘ of character ch in string s1. β•‘
╠═════════════════╬════════════════════════════════════════════╣
β•‘ strstr(s1,s2) β•‘ Returns a pointer to the first string s2 β•‘
β•‘ β•‘ in string s1. β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

The header file <cstring> defines several functions to manipulate C strings and arrays.

String Class in C++

There is no native β€œstring” data type in C++ but its <string> library class provides a string object that emulates a string data type. To make this available to a program, the library must be added with an #include <string> directive at the start of the program.

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char str[50];
int len;
cout << "Enter an array or string : ":
gets(str);
len = strlen(str);
cout << "Length of the string is : " << len;
return 0;
}

Like the <iostream> class library, the <string> library is part of the std namespace that is used by the C++ standard library classes. That means that a string object can be referred to as std::string, or more simply as string when using namespace std; again the directive must be at the start of the program.

Initializing Strings

A string β€œvariable” can be declared in the same way as other variables. The declaration may optionally initialized the variable using the = assignment operator, or it may be initialized later in the program. Additionally a string variable may be initialized by including a text string between parentheses after the variable name.

Text strings in C++ must always be enclosed with double quotes(β€œβ€).
Single quotes (β€˜β€™) are only used for character values of the char data type.

Any numeric values that are assigned to a string variable, are no longer a numeric data type, so attempting to add string values of β€œ4” and β€œ5” with the addition operator(+) would add up to β€œ45” instead of 9.

Converting Strings to other Data Types

Arithmetic cannot be performed on numeric values assigned to string variables until they are converted to a numeric data type. Luckily, there is a C++ <sstream> library provides a β€œstringstream” object that acts as an intermediary to convert strings to other data types.

Other features of a string variable can be revealed by calling its size(), capacity(), and empty() functions. Written below is short summary of other features.

  • a string variable can be emptied by assigning it an empty string (=β€œβ€) or by calling its clear() function.
  • Multiple string values can be concatenated by the + operator
  • A string can be can be appended to another string by the += operator or by calling its append() function.
  • A string can be compared to another string by the == operator or by calling its append() function.
  • A string can be assigned to a string variable using the = operator or by calling its assign() function.
  • The swap() function swaps the values of two string variables.
  • Substrings of a string can be sought with the find() function, or specialized functions such as find_first_of(), and a character retrieved from a specified index position by the at() function.

Next we will be focusing more on control structure of the flow such as while loops, do-while loops, and for loops in addition to using the switch case for complex conditional tests.

If you enjoy this, don’t miss the other articles in this order.

  1. [Intro to C++ : Your First Program]
  2. [Intro to C++ : Variables, Constants, & Data Types]
  3. [Intro to C++ : Using Expressions, Statements and Operators]
  4. [Intro to C++: Managing Arrays & Strings]
  5. [Intro to C++: Controlling the Flow]

CyberCode Twins πŸ‘Ύ πŸ‘Ύ

Written by

#TEDx SpeakersπŸŽ™οΈ| M.I.T Media Lab BC Alumni ⛓️| Top 5 IBM #SmartCities Finals πŸŒ‡ | πŸš€PR πŸ‡΅πŸ‡· LA | #TwitchDev #Blockchain #AI| CyberCodeTwins.com | shEOS.org