Your SlideShare is downloading. ×
0
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Computer Programming- Lecture 5
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Computer Programming- Lecture 5

6,674

Published on

C-Strings

C-Strings

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
6,674
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
29
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Lecture 5 C-StringsComputer Programming I 1
  • 2. Outline C-strings Functions for C-strings C-strings input C-strings output C-strings to numbers Computer Programming I 2
  • 3. Problems How do I store the names of students? How do I specify filenames? How to I manipulate text? Computer Programming I 3
  • 4. String TaxonomyComputer Programming I 4
  • 5. An Array Type for Strings C-strings can be used to represent strings of characters  C-strings are stored as arrays of characters  C-strings use the null character 0 to end a string  The Null character is a single character  To declare a C-string variable, declare an array of characters: char s[11]; Computer Programming I 5
  • 6. Arrays A series of elements (variables) of the same type Placed consecutively in memory Can be individually referenced by adding an index to a unique name Example, an array to contain 5 integer values of type int called item: int item[5]; 0 1 2 3 4 item int Computer Programming I 6
  • 7. An Array Type for Strings C-strings can be used to represent strings of characters  C-strings are stored as arrays of characters  C-strings use the null character 0 to end a string  The Null character is a single character  To declare a C-string variable, declare an array of characters: char s[11]; Computer Programming I 7
  • 8. C-string Details Declaring a C-string as char s[10] creates space for only nine characters  The null character terminator requires one space A C-string variable does not need a size variable  The null character(‘0’) immediately follows the last character of the string Example: s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9] H i M o m ! 0 ? ? Computer Programming I 8
  • 9. C-string Declaration To declare a C-string variable, use the syntax: char Array_name[ Maximum_C_String_Size + 1];  + 1 reserves the additional character needed by 0 Computer Programming I 9
  • 10. Initializing a C-string To initialize a C-string during declaration: char my_message[20] = "Hi there.";  The null character 0 is added for you Another alternative: char short_string[ ] = "abc"; but not this: char short_string[ ] = {a, b, c}; Computer Programming I 10
  • 11. C-string error This attempt to initialize a C-string does not cause the ‘0’ to be inserted in the array  char short_string[ ] = {a, b, c}; Computer Programming I 11
  • 12. C-style string A C-style string in C++ isThe declaration: basically an array of characters, terminated by achar name[10]="Hello"; null character (0) is equivalent When we count the length of the string, char name[10]={H,e,l,l,o,0}; we do not count the terminating null character. H e l l o 0 (the size of the array is 10, the length of the string is 5) Computer Programming I 12
  • 13. The declaration: If the size of the array is notchar name[]="Hello"; specified, then the array size would be equal to the is equivalent length of the string plus 1 char name[]={H,e,l,l,o,0}; H e l l o 0 (the size of the array is 6, the length of the string is 5) Computer Programming I 13
  • 14. The declaration: The declaration: char name[6]="H"; char name[]="H"; is equivalent is equivalentchar name[6]={H,0}; char name[]={H,0}; H 0 H 0 (the size of the array is 6, (the size of the array is 2, But the length of the string is 1) But the length of the string is 1) Computer Programming I 14
  • 15. Null string The declaration: (empty string) The declaration: char name[6]=""; char name[]=""; is equivalent is equivalentchar name[6]={0}; char name[]={0}; 0 0 (the size of the array is 1, (the size of the array is 1, the length of the string is 0) the length of the string is 0) Computer Programming I 15
  • 16. The declaration: char name[]="H"; H 0 (the size of the array is 2, is NOT equivalent the length of the string is 1)char name=H; H (this is not an array nor a string, it is simply a character) Computer Programming I 16
  • 17. char name[11]="John Connor"; J o h n C o n n o rNote: If you just want to have an array of characters,then this MAY be ok.Warning: if you want to use this as string with the C’sstandard string manipulation library, then you may runinto problems because the string is not null terminated. Computer Programming I 17
  • 18. Assignment With C-strings This statement is illegal: a_string = "Hello";  This is an assignment statement, not an initialization  The assignment operator does not work with C-strings Computer Programming I 18
  • 19. Assignment of C-strings A common method to assign a value to a C-string variable is to use strcpy, defined in the cstring library  Example: #include <cstring> … char a_string[ 11]; strcpy (a_string, "Hello"); Places "Hello" followed by the null character in a_string Computer Programming I 19
  • 20. #include <iostream>#include <cstring> strcpy()using namespace std;int main() { char source[] = "Judgement Day"; Copy one string into char dest[] = "Rise of the Machine"; another. Copy string strncpy(dest,source); source to dest, cout << "source = " << source << endl; cout << " dest = " << dest << endl; stopping after the} terminating null character has been moved. source = Judgement Day dest = Judgement Day WARNING : Make sure the destination string has enough allocated array space to store the new string. The compiler will not warn you about this, you MAY probably corrupted some part of the computer memory if your destination array of characters is not big enough to store the new string. This is DANGEROUS, so be careful !!! Computer Programming I 20
  • 21. int main() { char source[] = "Judgement Day"; char dest[] = "Rise of the Machine"; dest = source; . . . }WARNING : You cannot assign one string to another just as youcant assign one array to another !!!The compiler will give an error. Computer Programming I 21
  • 22. int main() { This is an initialization, it char dest[20] = "Judgement Day";} is valid.int main() { int main() { char dest[20]; char dest[20]; dest = "Judgement Day"; strcpy(dest,"Judgement Day");} } This is an assignment, it is NOT valid. Use strcpy to assign a c-string to another c-string WARNING : You cannot assign one string to another just as you cant assign one array to another !!! Use strcpy() function instead. Computer Programming I 22
  • 23. A Problem With strcpy strcpy can create problems if not used carefully  strcpy does not check the declared length of the first argument  It is possible for strcpy to write characters beyond the declared size of the array Computer Programming I 23
  • 24. A Solution for strcpy Many versions of C++ have a safer version of strcpy named strncpy  strncpy uses a third argument representing the maximum number of characters to copy  Example: char another_string[10]; strncpy(another_string, a_string_variable, 9); This code copies up to 9 characters into another_string, leaving one space for 0 Computer Programming I 24
  • 25. == Alternative for C-strings The = = operator does not work as expected with C-strings  The predefined function strcmp is used to compare C- string variables  Example: #include <cstring> … if (strcmp(c_string1, c_string2)) cout << "Strings are not the same."; else cout << "String are the same."; Computer Programming I 25
  • 26. strcmps logic strcmp compares the numeric codes of elements in the C-strings a character at a time  If the two C-strings are the same, strcmp returns 0  0 is interpreted as false  As soon as the characters do not match  strcmp returns a negative value if the numeric code in the first parameter is less  strcmp returns a positive value if the numeric code in the second parameter is less  Non-zero values are interpreted as true Computer Programming I 26
  • 27. #include <iostream>#include <cstring> strcmp()using namespace std; Compare one string to another startingint main() { with the first character in each string and char string1[] = "Hello"; continuing with subsequent characters char string2[] = "Hello World"; until the corresponding characters differ char string3[] = "Hello World"; or until the end of the strings is reached. char string4[] = "Aloha"; int n; n = strcmp(string1, string2); cout << string1 << "tt" << string2 << "t==> " << n << endl; Hello Hello World ==> -1 n = strcmp(string2, string3); cout << string2 << t << string3 << "t==> " << n << endl; Hello World Hello World ==> 0 n = strcmp(string3, string4); cout << string3 << t << string4 << "tt==> " << n << endl;} Hello World Aloha ==> 1 Computer Programming I 27
  • 28. #include <iostream> #include <cstring> using namespace std; int main() { char string1[] = "Hello"; char string2[] = "Hello"; if ( string1==string2 ) cout << "Same"; output: else Different cout << "Different"; }WARNING : You should not use the logical comparison to comparewhether two C-strings are identical.The compiler will NOT give you any compile-time errors nor warning,but you will not be getting the results you thought you would get. Computer Programming I 28
  • 29. #include <iostream> #include <cstring> using namespace std; int main() { char string1[] = "Hello"; char string2[] = "Hello"; if (strcmp(string1,string2)==0 ) cout << "Same"; output: else Same cout << "Different"; }Use strcmp() function instead for string comparison. Computer Programming I 29
  • 30. More C-string Functions The cstring library includes other functions  strlen returns the number of characters in a string int x = strlen( a_string);  strcat concatenates two C-strings  The second argument is added to the end of the first  The result is placed in the first argument  Example: char string_var[20] = "The rain"; strcat(string_var, "in Spain"); Now string_var contains "The rainin Spain" Computer Programming I 30
  • 31. The strncat Function strncat is a safer version of strcat  A third parameter specifies a limit for the number of characters to concatenate  Example: char string_var[20] = "The rain"; strncat(string_var, "in Spain", 11); Computer Programming I 31
  • 32. #include <iostream>#include <cstring> strcat()using namespace std;int main() { char dest[30] = "Rise of "; Appends one string to char source[] = "The Machine"; another. strcat() appends a copy of strcat( dest, source ); source to the end of cout << " dest = " << dest << endl; dest. The length of cout << "source = " << source << endl; the resulting string is} strlen(dest) + dest = Rise of The Machine strlen(source). source = The MachineWARNING : Make sure the destination string has enough allocatedarray space to store the new string. The compiler will not warn youabout this, you MAY probably corrupted some part of the computermemory if your destination array of characters is not big enough tostore the new string. This is DANGEROUS, so be careful !!! Computer Programming I 32
  • 33. char s1[12]="Hello"; char s2[]="World";s1 s2 H e l l o 0 W o r l d 0 strcat(s1,s2);s1 s2H e l l o W o r l d 0 W o r l d 0 Computer Programming I 33
  • 34. C-String functions in Cs Standard Library Must #include <cstring> Most common functions:  strlen() – get the length of the string without counting the terminating null character.  strncpy() - copy one string to another string  strcmp() - compare two string  strncat() - concatenates / join two string Computer Programming I 34
  • 35. C-string Output C-strings can be output with the insertion operator  Example: char news[ ] = "C-strings"; cout << news << " Wow." << endl; Computer Programming I 35
  • 36. C-string Input The extraction operator >> can fill a C- string  Whitespace ends reading of data  Example: char a[80], b[80]; cout << "Enter input: " << endl; cin >> a >> b; cout << a << b << "End of Output"; could produce: Enter input: Do be do to you! DobeEnd of Output Computer Programming I 36
  • 37. Simple C-String Input and Output must #include this for usingConsider this program : strlen() function #include <cstring> Declaring name to be an #include <iostream> array of characters using namespace std; int main() { To treat the array of characters as C- char name[10]; string, we just use the name of the cout << "Name => "; array when dealing with I/O stream. cin >> name; cout << "Name is [" << name << "]" << endl; cout << "Name length is " << strlen(name); } Standard function to return the length of the string Computer Programming I 37
  • 38. #include <cstring>#include <iostream>using namespace std;int main() { char name[10]; cout << "Name => "; cin >> name; cout << "Name is [“ << name << "]n"; cout << "Name length is “ << strlen(name);}Sample run 1: Sample run 2: Name => Hello thereName => hello Name is [Hello]Name is [hello] Name length is 5Name length is 5 [remark: the cin will stop[remark: no problem] scanning after the space character is encountered. Computer Programming I 38
  • 39. Reading an Entire Line Predefined member function getline can read an entire line, including spaces  getline is a member of all input streams  getline has two arguments  The first is a C-string variable to receive input  The second is an integer, usually the size of the first argument specifying the maximum number of elements in the first argument getline is allowed to fill Computer Programming I 39
  • 40. Using getline The following code is used to read an entire line including spaces into a single C-string variable  char a[80]; cout << "Enter input:n"; cin.getline(a, 80); cout << a << End Of Outputn"; and could produce: Enter some input: Do be do to you! Do be do to you!End of Output Computer Programming I 40
  • 41. getline syntax Syntax for using getline is cin.getline(String_Var, Max_Characters + 1);  cin can be replaced by any input stream  Max_Characters + 1 reserves one element for the null character Computer Programming I 41
  • 42. More C-String Input and Output Sample run:consider: Name => HelloThereHowAreYou#include <cstring> Name is [HelloThereHowAreYou]#include <iostream> Name length is 19using namespace std;int main() { char name[10]; cout << "Name => "; cin >> name; cout << "Name is [“ << name << "]n"; cout << “The Length: “ << strlen(name);}Warning: we have allocated only 10 characters to store the string, where has all the extra characters gone to?Answer : We have probably corrupted some part of the memory, this is DANGEROUS, so be careful !!!] Computer Programming I 42
  • 43. Input functions : character array input using cin.get(...)#include <iostream> sample run 1: only 9using namespace std; character alibabamuthuint main () { [alibabamu] read, NOT 10. char name[20]; user press cin.get(name,10); sample run 2: enter, stop ali reading cout << "[" << name << "]"; because n is [ali]} the default delimiter.Specifies the maximum number ofbytes to be filled into the character 9 characters read,array, in the case here, 10 character including 2 tab t characters.will be filled, meaning 9 characters sample run 3:will be read (NOT 10) from input ali baba muthustream, the 10th character is null [ali baba ]character ("0). Computer Programming I 43
  • 44. #include <iostream> sample run 1:using namespace std; same as alibabamuthu beforeint main () { [alibabamu] char name[20]; cin.get(name,10,z); sample run 2: user press enter, n cout << "[" << name << "]"; ali is read as baba} valid input muthu since n is [ali NOT the baba delimiter. ]the character z is used as delimiter the delimiter sample run 3: (which is z in this afizuddin case) is encounter, [afi] thus stop reading Computer Programming I 44
  • 45. #include <iostream>using namespace std;int main () { output: char name[20]; ab cde cin >> name; [ab] cout << "[" << name << "]";}#include <iostream>using namespace std; output:int main () { ab cde char name[20]; [ab cde] cin.get(name,10); cout << "[" << name << "]";} Remember : cin.get(...) read whitespaces as valid input character unless the whitespace is delimiter Computer Programming I 45
  • 46. Input functions : overcome delimiter problem using cin.getline(...)#include <iostream>using namespace std; sample run 1:int main () { mary [mary] This char name1[10],name2[10],name3[10]; peter solved the cin.getline(name1,10); [peter] delimiter john problem!! cout << "[" << name1 << "]n"; [john] cin.getline(name2,10); cout << "[" << name2 << "]n"; cin.getline(name3,10); cout << "[" << name3 << "]n";} Computer Programming I 46
  • 47. #include <iostream>using namespace std; sample run 1:int main () { marypeter [mary] char name1[10],name2[10],name3[10]; pan cin.getline(name1,10,p); john [eter cout << "[" << name1 << "]n"; pan cin.getline(name2,10,j); ] cout << "[" << name2 << "]n"; carl [ohn cin.getline(name3,10,a); c] cout << "[" << name3 << "]n";} Why? Computer Programming I 47
  • 48. Assigning Characters Into C-Strings#include <cstring>#include <iostream> Strings are treated justusing namespace std; like an array ofint main() { character values here. char str[11]; The null character is str[0] = H; str[1] = I; str[2] = 0; used to indicate the cout << str << endl; end of the string when for (int i=0; i<=9; i++) str[i] = A + i; processed by the str[i] = 0; standard library such cout << str << endl; as puts() function. str[5] = 0; for (int i=0; i<=10; i++) cout << "[" << static_cast<int>( str[i] ) << "]"; cout << endl; output: cout << str << endl; HI ABCDEFGHIJ str[5] = A; cout << str << endl; [65][66][67][68][69][0][71][72][73][74][0] system("pause"); ABCDE} ABCDEAGHIJ Computer Programming I 48
  • 49. #include <iostream>#include <cstring>using namespace std;int main() { char dest[30] = "Rise of "; char source[] = "The Machine"; dest = dest + source; cout << " dest = " << dest << endl; cout << "source = " << source << endl;} WARNING : You can not use arithmetic addition in order to concatenate two C-string. The compiler will give you compile-time errors. Computer Programming I 49
  • 50. Array of C-Strings The declaration: declares one string of which the maximum length is 29. char actor[30]; A c-string is an one-dimensional array of characters. How do I declared an array of c-strings? one solution: This declare an array of 5 strings, of whichchar actor[5][30]; the maximum length of the string is 30. That means, an array of strings is actually a two-dimensional array of characters. Computer Programming I 50
  • 51. char actor[4][10] = { "Arnold", "Nick", "Claire", "Kristanna" }; 0 1 2 3 4 5 6 7 8 9 actor[0] A r n o l d 0 actor[1] N i c k 0 actor[2] C l a i r e 0 actor[3] K r i s t a n n a 0 Computer Programming I 51
  • 52. Example:#include <iostream>#include <cstring>using namespace std;int main() { char actor[4][30] = { "Sylvester Stallon", "Nick Stahl", "Claire Danes" }; char anotherActor[30] = "Arnold Schwarzenegger"; cout << anotherActor << endl; cout << actor[0] << endl; strcpy ( actor[0], anotherActor ); strcpy ( actor[3], "Kristanna Loken" ); for (int i=0; i<=3; i++) cout << i << " " << actor[i] << endl;} Arnold Schwarzenegger Sylvester Stallon 0 Arnold Schwarzenegger 1 Nick Stahl 2 Claire Danes Computer Programming I 3 Kristanna Loken 52
  • 53. C-String to Numbers "1234" is a string of characters 1234 is a number When doing numeric input, it is useful to read input as a string of characters, then convert the string to a number  Reading money may involve a dollar sign  Reading percentages may involve a percent sign Computer Programming I 53
  • 54. C-strings to Integers To read an integer as characters  Read input as characters into a C-string, removing unwanted characters  Use the predefined function atoi to convert the C-string to an int value  Example: atoi("1234") returns the integer 1234 atoi("#123") returns 0 because # is not a digit Computer Programming I 54
  • 55. C-string to long Larger integers can be converted using the predefined function atol  atol returns a value of type long Computer Programming I 55
  • 56. C-string to double C-strings can be converted to type double using the predefined function atof atof returns a value of type double  Example: atof("9.99") returns 9.99 atof("$9.99") returns 0.0 because the $ is not a digit Computer Programming I 56
  • 57. Library cstdlib The conversion functions atoi atol atof are found in the library cstdlib To use the functions use the include directive #include <cstdlib> Computer Programming I 57
  • 58. C-String conversion to numbers #include <iostream> #include <cstring> using namespace std; int main() { char str1[] = "1234"; char str2[] = "0123"; char str3[] = " 123"; char str4[] = "$123"; char str5[] = "12.34"; int n1,n2,n3,n4,n5; double d1,d2,d3,d4,d5; long l1,l2,l3,l4,l5; n1 = atoi(str1); n2 = atoi(str2); n3 = atoi(str3); n4 = atoi(str4); n5 = atoi(str5); d1 = atof(str1); d2 = atof(str2); d3 = atof(str3); d4 = atof(str4); d5 = atof(str5); l1 = atol(str1); l2 = atol(str2); l3 = atol(str3); l4 = atol(str4); l5 = atol(str5); cout << n1 << " " << n2 << " " << n3 << " " << n4 << " " << n5 << endl; cout << d1 << " " << d2 << " " << d3 << " " << d4 << " " << d5 << endl; cout << l1 << " " << l2 << " " << l3 << " " << l4 << " " << l5 << endl; } 1234 123 123 0 12 output: 1234 123 123 0 12.34 1234 123 123 0 12 Computer Programming I 58
  • 59. Predefined Functionstoupper(char_exp) – convert lowercase character to uppercasetolower(char_exp) – convert uppercase character to lowercaseisupper(char_exp) – tests if character is an uppercase letterislower(char_exp) – tests if character is a lowercase letterisalpha(char_exp) – tests if character is alphanumericisdigit(char_exp) – tests if character is digitisspace(char_exp) – tests if character is white-space character Computer Programming I 59
  • 60. Predefined Functions (cont.)atoi(str_exp)  ingr1 = atoi(str1); Parses string interpreting its content as a number and returns an int valueatof (str_exp)  dbl1 = atof(str1); Parses string interpreting its content as a floating point number and returns a value of type doubleatol (str_exp)  lng1 = atol(str1); Parses string interpreting its content as a number and returns a long value. Computer Programming I 60
  • 61. The EndComputer Programming I 61

×