
Topic 3 C-Strings Objectives You should be able to describe: C-String Fundamentals (Ch.7, section 7.10) Initialization Accessing Characters in String Reading and Outputting Strings Library Functions Problem Solving Strings (Textbook chapter 13) Strings are represented as arrays of characters, e.g. char input[5]; input[2] = 'x'; Strings The string may be of any length, but a special character, the 'null' character, is guaranteed to occur somewhere in the array. The null character (‘\0’) denotes the end of the string. String Initialization String initialization char color[] = "blue"; Creates 5 element char array named color last element is '\0‘ b l u e \0 0 1 2 3 4 Alternative for character array char color[] = { ‘b’, ‘l’, ‘u’, ‘e’, ‘\0’ }; String Initialization (ctd’) char string1[20] = “Hello World"; H e l l o W o r l d \0 …. 0 1 2 3 4 5 6 7 8 9 10 11 12 … 19 Hello World cout<<string1; Outputs up to the NULL character \0. What happens if there is more than one NULL character? String Initialization (ctd’) char string1[20] = “Hello World"; If there is more than one NULL character \0, it outputs up to the FIRST one string1[2]=‘\0’; H e l o W o r l d …. \0 \0 0 1 2 3 4 5 6 7 8 9 10 11 12 … 19 cout<<string1; He Accessing Characters in Strings We can access individual characters in a string directly, as usual, using the array index notation. E.g. char color[] = "blue"; cout<< color[2]; // prints the character u cout<<color[0]; // prints the character b color[0]=‘f’; //assigns the character f to position 0 cout<<color[0]; // prints the character f, following // previous assignment Reading Strings Assign input to character array word: char word[20]; cin>>word; Only array name is supplied!! Reads characters until space, tab, newline or EOF String entered should not be longer than 19 characters in this example (20th location in the array reserved for null ‘\0’) Outputting Strings Only array name is supplied!! Outputting cout<<word; Outputs the string until the terminating null character is encountered. Example program #include <iostream> using namespace std; int main() { char str[20]; int i; cout<<"Enter a word: "; cin>>str; cout<<"The word is: "<<str<<endl; cout<<"The word with spaces between letters is: "<<endl; i=0; while (str[i]!=‘\0’) //while we have not yet reached the end of string { cout<<str[i]<<" "; i++; } cout<<endl; return 0; } Example code: What is the output? char A[25]; cin >> A; for(i=0; A[i]!='\0'; i++) ; for(i--; i>=0; i--) cout << A[i]; Counting letters program #include <iostream> //Counts the number of times the letter h appears in string using namespace std; int main() { int i, count=0; ; char word[5] ; cout << "Type in a word: " ; cin >> word; for(i=0; word[i]!=‘\0’; i++) if (word[i]==‘h’) count++; if (count==1) cout<<"The letter h appears 1 time"<<endl; else cout<<"The letter h appears " << count<<"times"<<endl; return 0; } C-String Input and Output (continued) cin cannot be used for C-string input If the string contains a space, the cin object will only read up to the space (or newline character) Example of program fragment: char str[20]; Hello World! cout<<“Enter a string:”; cin>>str; Hello cout<<“String entered is:”<<str; C-String Input and Output (continued) Need to use cin.getline() for C-string input cin.getline() function syntax: cin.getline(str, terminatingLength, terminatingChar) str is C-string or character pointer variable terminatingLength is integer indicating maximum number of input characters terminatingChar is optional character specifying terminating character (default is newline character \n) Example: cin.getline(str,81,’\n’); Read characters typed at the terminal into the character array named str until either 80 characters are entered (81st character reserved for NULL \0) or the ENTER key is detected. C-String Input and Output (continued) Figure 13.2: Inputting a C-string with cin.getline() C-String Input and Output (continued) C-String Input and Output Example Source:Bronson, Program Development and Design Using C++, Third Edition Caution: The Phantom newline Character Problems can occur when both the cin and the cin.getline are used together to accept data. See example program (next slide). The Phantom newline Character #include <iostream> using namespace std; int main() { int x; char str[81]; cout<<"Enter an integer:"; cin>>x; cout<<"Your integer is "<<x<<endl; cout<<"Enter a string:"<<endl; cin.getline(str,81); cout<<"Your string is:"<<str<<endl; return 0; } Program output Enter an integer: 23 Your integer is 23 Enter a string: Your string is: Program does not wait for string to be entered in the second prompt. After the integer 23 is entered the rest of the output appear immediately with no further interaction. Program Output (continued) The reason for this is the newline (\n) character at the end of the integer entered. \n character remains in the buffer after we enter the integer and press Enter. The next call cin.getline picks up the Enter key as the next character and immediately terminates any further input. Solution to the Phantom newline Use cin.ignore() after the cin and before the cin.getline(). This will ingore the next character on the input stream. Solution to the newline Character problem #include <iostream> using namespace std; int main() { int x; char str[81]; cout<<"Enter an integer:"; cin>>x; cout<<"Your integer is "<<x<<endl; cin.ignore(); cout<<"Enter a string:"<<endl; cin.getline(str,81); cout<<"Your string is:"<<str<<endl; return 0; } Library Functions C++ does not provide built-in operations for complete arrays Assignment and relational operations not provided for strings Extensive collections of C-string handling functions and routines included as part of C++’s standard library Effectively supply string assignment, comparison, and other useful string operations String Library Routines (Required Header File Is cstring) Function Description Example strcpy(str1, str2) Copies string str2 to strcpy(s1,”hello”) string str1 including ‘\0’. str1 must be large enough to hold str2. The original value to str1 is destroyed. strlen(str1) Returns the length of the strlen(“hello hi”) string str1, i.e. the number of characters returns 8 excluding the null character ‘\0’. String Library Routines (Required Header File Is cstring) Function Description Example strcat(str1, str2) Appends str2 at the end char s1[20]=“hello”; of str1. str1 must be strcat(s1,”world”); large enough to hold both str1 before appending s1 helloworld and str2. contains strcmp(str1, str2) Compares str1 and strcmp(“cat”,”dog”) str2 and returns a negative, zero, or positive Returns a negative value depending on value. whether str1 is less than, equal to, or greater than str2 in alphabetic order. strcmp examples strcmp(“hello”, “hillo”) returns a negative value. (e is less than i). strcmp(“Hello”,”hello”) returns a negative value. (Upper case letters are smaller than lower case in alphabetic order). strcmp(“Hello”, “Hellooo”) returns negative. (Same prefix but longer string is larger). strcmp(“Hello”,”H5llo”) returns positive. (Digits are smaller than letters in lexicographic order). strcmp(“hello”,”hello”) returns 0. (Strings are the same). Example program using string functions #include <iostream> #include <cstring> using namespace std; int main() { const int MAXELS = 50; char string1[MAXELS] = "Hello"; char string2[MAXELS] = "Hello there"; if (strcmp(string1, string2)<0) cout << string1 << " is less than " << string2 << endl; else if (strcmp(string1, string2)==0) cout << string1 << " is equal to " << string2 << endl; else cout << string1 << " is greater than " << string2 << endl; Example program using string functions cout << "The length of string1 is " << strlen(string1)<< endl; cout << "The length of string2 is " << strlen(string2)<< endl; strcat(string1," World!"); cout << "\nAfter concatenation, string1 contains "<< string1; cout << "\nThe length of this string is "<< strlen(string1)<<endl; strcpy(string1, string2); cout << "\nAfter copying string2 to string1, the value in string1 is:" << string1; cout << "\nThe length of this string is "<<strlen(string1)<<endl; return 0; } Program for copying a string without the use of cstring function #include <iostream> using namespace std; int main() { const int MAXCHARS = 81; char str1[MAXCHARS]; // enough storage for a complete line char str2[MAXCHARS]; // enough storage for a copy of message int i; cout << "Enter a sentence: "<<endl; cin.getline(str2,81); i=0; while (str2[i] != '\0') // check for the end-of-string { str1[i] = str2[i]; // copy the element to string i++; } str1[i] = '\0'; // NOTE!!! terminate the first string cout<<"The copied string is: "<<str1<<endl; return 0; } Example: Problem of searching a string Write a function that takes a string and a character and returns true (i.e. 1) if the character occurs in the string, and false otherwise. Test your function by writing a program that reads a word and a character from the user and checks if the character occurs in the string. Print appropriate messages. 31 Program for searching a string #include <iostream> using namespace std; int find(char s1[], char ch); // the function prototype int find(char s[], char ch) { int i, found=0; //set found to false i=0; while (s[i]!='\0') { if (s[i]==ch) found=1; i++; } return found; } 32 Program for searching a string (ctd’) int main() { char str1[20],ch1; cout <<"Enter a word: "; cin >> str1; cout <<"Please enter a character to look for: "; cin >> ch1; if (find(str1,ch1)==1) cout<<"The charecter "<< ch1<<" appears."<<endl; else cout<<"The character does not appear in the word."<<endl; return 0; } 33 A better way to write the function find int find(char s[], char ch) { int i; //we do not need the boolean variable found i=0; while (s[i]!='\0') { if (s[i]==ch) return 1; //this will exit the function i++; } return 0; //if we are here it means we didn’t find ch } 34 Searching a string II Function takes a string and a character and returns true if the character occurs in the string.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages37 Page
-
File Size-