Presentation is loading. Please wait.

Presentation is loading. Please wait.

Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Arrays, Character Strings and Standard Type String ~ Collection.

Similar presentations


Presentation on theme: "Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Arrays, Character Strings and Standard Type String ~ Collection."— Presentation transcript:

1 Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Arrays, Character Strings and Standard Type String ~ Collection of Objects

2 2 Overview  Motivation  Introduction to Array  Array Subscripting and Element Manipulation  Array Initialization  Constant Arrays  Multi-Dimensional Arrays  Unsized Array Initialization  Representing Strings as Character Strings  Functions to Manipulate C-Strings  C++ String Type

3 Department of Computer Science and Engineering, HKUST 3 Arrays, Character Strings and Standard Type String Motivation

4 4  Suppose you need to find the maximum value of 5 int values, Value1, Value2, …, Value5.  The following code segment computes that value. int MaximumSoFar = Value1; if(Value2 > MaximumSoFar) MaximumSoFar = Value2; if(Value3 > MaximumSoFar) MaximumSoFar = Value3; if(Value4 > MaximumSoFar) MaximumSoFar = Value4; if(Value5 > MaximumSoFar) MaximumSoFar = Value5;

5 5 Motivation  Notice that you need to have a separate if statement for each integer variable, because each variable is totally independent of other variables, although the variables are similar.  Now suppose that you need the maximum value from a group of 500 integer values Value1 through Value500. Because the variables are independent, you cannot simply introduce iteration into the solution. Using the approach as above, with a separate if statement for each integer variable, this resulting very large code segment would be both clumsy and error prone.  So, what should we do? Array!

6 Department of Computer Science and Engineering, HKUST 6 Arrays, Character Strings and Standard Type String Introduction to Array

7 7 Arrays  An array is a collection of data elements that are of the same type (e.g., a collection of integers, characters, doubles). S YNTAX : [ ]; The array elements are all values of the type. The size of the array is indicated by, the number of elements in the array. must be an int constant or a constant expression.  It must be a compile-time deductible integral constant

8 8 Example  Single-dimensional arrays are essentially lists of information of the same type that are stored in contiguous memory locations in index order.  For example // array of 5 // un-initialized // ints int A[5]; Memory Address 2004 2008 2012 Variables in memory Memory Variables Name A[1] A[3] A[0] 2016 2000 A[2] A[4]

9 Department of Computer Science and Engineering, HKUST 9 Arrays, Character Strings and Standard Type String Array Subscripting and Element Manipulation

10 10 Array Subscripting  Arrays provides a good way to name a collection, and to reference its individual elements using [ ] operator.  Suppose, we declare a collection of 5 integers int A[5]; // array of 5 ints To access an individual element we must apply a subscript with index to array A, In C++, first element of array has index 0  A[0]. Second element of array has index 1  A[1], and so on. Last element has an index one less than the size of the array  A[4].

11 11 Example - Array Subscripting // array of 5 un-initialized ints int A[5]; A[2]=1; int x=A[2]; Memory Address 2004 2008 2012 Variables in memory Memory Variables Name A[1] A[3] A[0] 2016 1 1 2000 A[2] A[4]

12 12 Inputting a List of Values to Arrays #include using namespace std; int main(){ const int MaxSize = 10000; int A[MaxSize]; int n = 0; int CurrentInput; while(n >CurrentInput){ A[n] = CurrentInput; n++; } // List A of n elements has already been set int i; for (i=0; i<n; i++) cout << A[i] << " "; cout << endl; return 0; }

13 13 Example – Bad Subscripting  C++ does not provide an automatic way for ensuring the proper subscripts are used.  For example, the following code segment does not generate an error message. int B[5]; B[-5] = 1; Instead of an error message, it modifies another memory location (5 integers before the array B[0]).  If that location is used to store data, the program may result in incorrect result.  If that location is used to store code, the program may result in runtime-error (core dump).  Many other possible errors……

14 14 Array Element Manipulation #include using namespace std; int main(){ int A[5], i=3, j=2, k=4; A[0]=1; A[1]=5; A[i]=2; A[j]=A[i]+1; A[j+1]=A[i]+A[0]; A[A[j]]=12; // assume the next input value is 3 cin >> A[k]; return 0; } Memory Address 2004 2008 2012 Variables in memory Memory Variables Name A[1] A[3] 1 1 A[0] 2016 5 5 3 3 12 3 3 2000 A[2] A[4]

15 Department of Computer Science and Engineering, HKUST 15 Arrays, Character Strings and Standard Type String Array Initialization

16 16 Array Initialization  Array elements are un-initialized unless there is explicit initialization.  Elements in the array can be initialized in the following manner. int A[5] = {5,4,3,2,1}; cout << "A[3]= " << A[3]; A[3] = -1; cout << "A[3]= " << A[3]; Memory Address 2004 2008 2012 Variables in memory Memory Variables Name A[1] A[3] 5 5 A[0] 2016 4 4 3 3 2 -1 1 1 2000 A[2] A[4]

17 17 Example Definitions  Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000;  Then the following are all legal array definitions. int A[10];// array of 10 ints char B[MaxStringSize];// array of 80 chars double C[M*N];// array of 800 doubles int Values[MaxListSize];// array of 1000 ints  How about this? Is it valid? int i=5; int A[i]; // INVALID, since size must be an int // constant or a constant expression

18 Department of Computer Science and Engineering, HKUST 18 Arrays, Character Strings and Standard Type String Constant Arrays

19 19 Constant Arrays  As in other type definitions, the modifier const can be applied in an array definition. As usual, after applying the initialization, the element is treated as constant.  For example, const int A[2] = { 10, 1000 }; With the const definition in effect, the following statements are invalid. A[0] = 20; // illegal cin >> A[1];// illegal

20 Department of Computer Science and Engineering, HKUST 20 Arrays, Character Strings and Standard Type String Multi-Dimensional Arrays

21 21 Two-Dimensional Arrays  In addition to defining one-dimensional arrays, it is also possible to define multi-dimensional arrays of data elements. The simplest form of the multi-dimensional array is two- dimensional array.  For example, // 2-D array of 30 uninitialized ints int A[3][10]; A 4 5 6 3 0 2 8 9 7 1 -- 0 2 1

22 22 Two-Dimensional Arrays  To access element in the array, we can use subscript operator, for example: // 2-D array of 30 uninitialized chars char A[3][10]; A[1][2] = ‘a’; A 4 5 6 3 0 2 8 9 7 1 -- 0 2 1 ‘a’ --

23 23 Example #include using namespace std; int main(){ int num[3][4]; for(int i=0; i<3; i++){ for(int j=0; j<4; j++){ num[i][j] = (i*4)+j+1; // now print them out cout << num[i][j] << “ ”; } cout << endl; } return 0; } num[i][j] 3 0 2 1 0 2 1 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 11 12

24 24 Two-Dimensional Array Initialization  Two-dimensional arrays can be initialized the same as single-dimension ones.  For example, the following initializes sqrs with the numbers 1 through 10 and their squares. int sqrs[10][2] = { 1,1, 2,4, 3,9, 4,16, 5,25, 6,36, 7,49, 8,64, 9,81, 10,100 };  Alternatively, you can write the preceding declaration as follows. int sqrs[10][2] = { {1,1}, {2,4}, {3,9}, {4,16}, {5,25}, {6,36}, {7,49}, {8,64}, {9,81}, {10,100} };

25 25 Multi-Dimensional Arrays  C++ allows array of more than two dimensions. The exact limit is determined by the compiler.  The general form of a multi-dimensional array declaration is as follows. S YNTAX : [ ][ ][ ] … [ ];  Example: // un-initialized 3 dimensional array int A[3][4][5];

26 26 Multi-Dimensional Arrays  Arrays of more than three dimensions are not often used.  Most cases a maximum of 3 dimensions will suffice for programming. Actually, single dimension C++ arrays are the commonest.  In multi-dimensional arrays, it takes the computer time to compute each index. This means accessing an element in a multi-dimensional array can be slower than accessing an element in a single-dimensional array.

27 Department of Computer Science and Engineering, HKUST 27 Arrays, Character Strings and Standard Type String Unsized Array Initialization

28 28 Unsized Array Initialization  If, in an array initialization statement, the size of the array is not specified, the C++ compiler automatically creates an array that is big enough to hold all the initializes present. For example: int A[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; Then, compiler will create an array of size 8 to hold all the initial values. 4 5 6 3 0 2 7 1 1 1 A 2 2 3 3 4 4 5 5 6 6 7 7 8 8

29 29 Unsized Array Initialization  Unsized array initializations are not restricted to one-dimensional arrays. For multi-dimensional arrays, you must specify all but the leftmost dimension. For example: int sqrs[][2] = { {1,1}, {2,4}, {3,9}, {4,16}, {5,25}, {6,36}, {7,49}, {8,64}, {9,81}, {10,100} }; Then, compiler will create an two-dimensional array of size 10x2 to hold all the initial values. 0 1 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 0 1 2 3 4 5 6 7 8 9 sqrs 1 1 4 4 9 9 16 25 36 49 64 81 100

30 Department of Computer Science and Engineering, HKUST 30 Arrays, Character Strings and Standard Type String Representing Strings as Character Strings

31 31 Representing Strings as Character Strings  C++ provides another initialization style for char arrays to support the representation of character strings.  For example, char letters[] = “Computer Sci.”; The first 13 elements of the array – letters[0] through letters[12] – get their initialization character from the corresponding position in the initialization string, i.e., letters[0] gets the first character, i.e. ‘ C ’ letters[1] gets the second character, i.e. ‘ o ’ … and so on.

32 32 Representing Strings as Character Strings  The last array element letters[13] is initialized to the null character ‘ \0 ’.  Actually the way that we initialize the array letters above is the same as writing, char letters[] = {‘C’,‘o’,‘m’,‘p’,‘u’,‘t’,‘e’, ‘r’,‘ ’,‘S’,‘c’,‘i’,‘.’,’\0’};  The size of the array is 14, instead of 13, since C++ representation for character strings includes a null character at the end of the string. Null character (‘\0’) is used to mark the end of a character string. Its ASCII code is 0

33 33 String VS. Character  A character is simply stored in a 8-byte memory location  A string is stored as a continuous character array, terminated by the null character  Example: “a” and ‘a’ are different “a” is represented as an array of size 2 ‘a’ is simply stored in one memory location  Therefore, you cannot directly compare them (“a” == ‘a’)// ERROR a a \0 a a

34 34 Character String – Escape Sequence  In a program text, we can only type a “printable character” (A-Z, a-z, 0-9, punctuations, etc.)  A character string needs some special characters. Newline (to instruct the program print the next character on a new line). Null character, etc.  These characters cannot be typed as usual in C++. Newline is represented as ‘\n’ Tab can be represented as ‘\t’ Null character is represented as ‘\0’ Double quote is represented as ‘\”’ Forward slash is represented as ‘\\’

35 35 Character String – Escape Sequence  Note that each escape sequence is represented (typed) as two characters in the program text.  But they are stored as ONE character (can be stored in a single char variable).

36 36 How to determine the length of a character string? int main( ){ char message[ ] = “Hello World”; int len = 0; for (int i=0; message[i]; i++, len++ ) ; cout << “length of \”” << message << “\”: “ << len << endl; return 0; }  length of “Hello World”: 11 Comma is used to separate several expressions. The return value is the last (the rightmost) expression.

37 37 String Literal  It is not legal to have a line break within a string literal in C++: // this is not legal “Computer Science and Engineering, The Hong Kong University of Science and Technology.”;  However, the following is OK: “Computer Science and Engineering,” “The Hong Kong University of Science and Technology.”;  And, of course, it is legal for a string literal to contain a newline character: “Please enter an integer:\n”;

38 Department of Computer Science and Engineering, HKUST 38 Arrays, Character Strings and Standard Type String Functions to Manipulate C-Strings

39 39 Functions to Manipulate C-Strings  C++ supports a wide range of functions that manipulate character strings. The most common are Note: These functions use the standard header file cstring. Make sure the destination array contains sufficient space to store the result. Function Description strcpy(s1,s2) Copies s2 into s1. strncpy(s1,s2,n) Copies s2 into s1, max. n characters including the null character. strcat(s1,s2) Concatenates s2 onto the end of s1. strncat(s1,s2) Concatenates s2 onto the end of s1, max. n, s1 always concluded with a null character. strlen(s) Returns the length of s, not including the null character. strcmp(s1,s2)Returns 0 if s1 and s2 are the same; less than 0 if s1 s2.

40 Department of Computer Science and Engineering, HKUST 40 Arrays, Character Strings and Standard Type String C++ String Type

41 41 C++ String Type  The standard C++ library provides an object string type to complement the character string used earlier: string Name1; // remember #include string Name2; // and using namespace std;  A string variable may be assigned the value of a string literal or another string variable: Name1 = “Tommy”; // “Tommy” is called a string literal Name2 = Name1;

42 42 String Initialization  A string variable may be initialized at the point of declaration: string word1 = “Hello”; string word2 = word1;  It is, however, not legal to assign a char or int value to a string in the declaration: string string1 = ‘N’; // illegal string string2 = 88;

43 43 Strings are C++ Classes  Like the input and output streams, cin and cout, string variables in C++ are actually object of the standard string class. (More about this will be covered later)  As string is a class in C++, every string has a number of associated functions that we can use to perform operations on the string. length(), empty(), compare(), at(), insert(), substr(), find()  Also, it supports a number of operators +, ==, !=, >, =, <=, []

44 44 Function: Length of a String  The length of a string is the number of characters it contains, including whitespace characters, if any.  By calling the function length(), we can obtain the length of the string. string str = “Adam Ng”; int sLength = str.length();// length = 7

45 45 Function: Testing if a String is Empty  The boolean function empty() returns true if the string variable currently holds no characters and false otherwise.  For example, one might use this function to determine whether a read attempt actually placed any characters into the target string: string str = “”; cin >> str; if(str.empty()) cout << “Read failed” << endl;  Of course, the test is only useful if you make certain that str is empty before attempting to read something onto it.

46 46 Function: String Concatenation  Two strings may be concatenated; that is, one may be appended to another: string str1 = “Hello”; string str2 = “world”; string str = str1 + “, “ + str2 + “!”;  Here, the concatenation operator (+) is used to combine several strings, variable and literal and the result is assigned to str.  The effect of the statement above is the same as: string str = “Hello, world!”;  You may use the concatenation operator to combine string variables, string literals and characters: str = str + ‘\n’;  However, you cannot use concatenation operator to combine two string literals.

47 47 Function: Comparing Strings For Equality  Two strings may be compared for equality using the usual equals relational operator (==). So we can write the following: string str1 = “Hello”; string str2 = str1 + str1; string str3 = “HelloHello”; if(str2 == str3) cout << str2 << “ equals ” << str3 << endl; else cout << str2 << “ doesn’t equal ” << str3 << endl;

48 48 Function: Comparing Strings For Equality  You can also use the not-equals operator (!=) with string variables: string str2 = “”; while(str2 != str3) str2 = str2 + str1;  The other relational operators (, >=) can also be used with C++ string variables. According to lexicographical order (or dictionary order).

49 49 Function: Lexicographic Comparison  Two strings can also be compared by using the function int compare();  The statement str1.compare(str2) returns: A negative value, if str1 < str2. Zero, if str1 == str2 ; A positive value, otherwise.  The same return value as strcmp(str1,str2)

50 50 Example: Lexicographic Comparison  Given the strings: string TA1 = “Pakming”; string TA2 = “Pakming Cheung”; string TA3 = “adam”; string TA4 = “Andrew”; the compare function would behave as follows: int c1 = TA1.compare(TA2); // Ans: c1 < 0 int c2 = TA1.compare(TA3); // Ans: c2 < 0 int c3 = TA2.compare(TA4); // Ans: c3 > 0 int c4 = TA1.compare(TA1); // Ans: c4 == 0

51 51 Function: Accessing String Elements  We can access the character at a particular position in a string variable using function at(int position).  For example string str = “Adam is good”; char ch1 = str.at(5);// ch1 == ‘i’  Note that the positions in a string are numbered sequentially, starting at zero, so for(int i=5; i<8; i++) cout << str.at(i) << ‘\t’; would print: i s

52 52 Function: Accessing String Elements  The character at a particular position in a string can also be accessed by subscript operator.  For example string str = “Adam is good”; char ch1 = str[5];// ch1 == ‘i’  Note that the positions in a string are numbered sequentially, starting at zero, so for(int i=5; i<8; i++) cout << str[i] << ‘\t’; would print: i s

53 53 Function: Inserting a String into Another  A string can be inserted into another string at a particular position using function insert(int startindex, string s) ;  For example: string Name = “Adam Ng”; string MiddleInitial = “ C. H.”; Name.insert(4, MiddleInitial); cout << Name << endl; prints: Adam C. H. Ng

54 54 Function: Extracting a Substring  A substring of a string can be extracted and assigned to another by using function: string& substr(int startcopy, int numtocopy);  For example: string Name = “Adam Ng”; string substring = Name.substr(5,2); cout << Name << endl << substring << endl; prints: Adam Ng Ng

55 55 Function: Erasing a Substring  A substring can be deleted from a string by using the function string& erase(int starterase, int numtoerase);  For example: string Name = “Adam Ng”; Name.erase(0,5); cout << “New name ” << Name << endl; prints: Ng

56 56 Function: Searching for a Substring  A string can be searched for an occurrence of a substring by using the function: int find(string s, int startsearch);  For example: string Name = “Adam Ng”; int loc = Name.find(“am”, 0); int loc2 = Name.find(“am”, 3); cout << loc << “ “ << loc2 << endl; prints: 2 -1

57 57 Function: Conversion to C-Strings  A string can be converted to C-Strings by using const char* c_str( );  For example: string Name = “Adam Ng”; cout << strcmp( Name.c_str(), “Adam Ng” ) << endl; prints: 0  We will talk more about this later when we are discussing pointer.

58 58 C++ String Type  There are many more functions presented in the C++ string  If you are interested, you may refer to the document: http://msdn.microsoft.com/library/default.asp?url=/library/en- us/vcstdlib/html/vclrf_string_basicstring_members.asp http://msdn.microsoft.com/library/default.asp?url=/library/en- us/vcstdlib/html/vclrf_string_basicstring_members.asp


Download ppt "Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Arrays, Character Strings and Standard Type String ~ Collection."

Similar presentations


Ads by Google