Intro to C++: Managing Arrays & Strings

shEOSBlockedUnblockFollowFollowingMay 1What’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 ArraysYou 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 Elementsint mike[5] = {19, 10, 8, 17, 9}// change 4th element to 9mike[3] = 9;// take input from the user and insert in third elementcin >> mike[2];// take input from the user and insert in (i+1)th elementcin >> mike[i];// print first element of the arraycout << mike[0];// print ith element of the arraycout >> mike[i-1];Character ArraysAn array of characters can be used to store a string of text if the final elements contains the special null character.

For example:char name[5] = {'p', 'n', 'o', 'p', ''};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 ArraysCollectively 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 StringC++ 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.


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 StringsA 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 TypesArithmetic 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 + operatorA 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.

[Intro to C++ : Your First Program][Intro to C++ : Variables, Constants, & Data Types][Intro to C++ : Using Expressions, Statements and Operators][Intro to C++: Managing Arrays & Strings].

. More details

Leave a Reply