> str1; str2 = str1; //assignment is OK cout << "\nCopy of string 1 is : " << str2; cout << "\nEnter a string"; cin >> str2; if (str1 < str2) //comparison is OK cout << str1 << ”is less than” << str2 ; else cout or equal to” << str1 ; cout << "\nThe capasity of the str2 is " << str2.capacity(); cout << "\nThe size (lenght) of the str2 is " << str2.size(); }">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright  Hannu Laine C++-programming Part 5 Strings.

Similar presentations

Presentation on theme: "Copyright  Hannu Laine C++-programming Part 5 Strings."— Presentation transcript:

1 Copyright  Hannu Laine C++-programming Part 5 Strings

2 HL1 In C-language a character array with terminating zero is used as a string. C-library contains many string manipulation functions (string.h). There are many disadvantages in C-like strings: They can not be assigned with assignment operator. They can not be compared wit comparison operators. They cannot expand automatically, to mention some of the drawbacks. Now when we have learned basics of classes, we would be able to define a class string for example in the following way and implement its operation functions: class string { public: string(const char *string0=“”); string operator+(const string &s2) const; const string &operator=(const string &right); //and many other operators and member // functions private: char *c_string; }; But it is not necessary to implement it ourselves, because it is done in C++ standard library. We only have to include the header file and use it. #include Class string

3 HL2 Advantages: You don’t have to give the length in the declaration. Memory area expands automatically. Assignment works (is real deep copy). Comparison can be done with comparison operator (means alphabetical order ). Input (>>) and output (<<) operators are defined for string. String example Simple example program: #include using namespace std; void main (void) { string str1, str2; cout << "\nEnter a string"; cin >> str1; str2 = str1; //assignment is OK cout << "\nCopy of string 1 is : " << str2; cout << "\nEnter a string"; cin >> str2; if (str1 < str2) //comparison is OK cout << str1 << ”is less than” << str2 ; else cout or equal to” << str1 ; cout << "\nThe capasity of the str2 is " << str2.capacity(); cout << "\nThe size (lenght) of the str2 is " << str2.size(); }

4 HL3 Basic operations of string Actually string is instantiated from the class template basic_string in the following way: typedef basic_string string; We will learn about class templates later. Constructors string s1; //default string s2(”abcdefg”); //initialising with c-string string s3(10, ’A’); //initialising with n characters Assignment operator s1 = ”abcde”; //assigning a c-string s2 = ’X’; // assigning a character s3 = s1; // assigning another string Input and output operators are defined cout << s1; //display a string cin >> s1; //input is delimited by white space getline(cin, s2); //read a whole line More about assignment (two expressions are same): s1 = s2; s1.assign(s2); Accessing individual characters (indexing and at member function): char chr; chr = s1[ i ]; // rigth vals1[ i ] = ’X’; //left val chr = s1.at( i ); // rigth vals1.at( i ) = ’X’; // -”-

5 HL4 Concatenation and comparison Concatenation string s1(”Espoo-”); string s2(”Vantaa ”); string s3(”xxxTechnicalxxx”); string s4; s4 = s1 + s2; s1+=s2; s1.append(s2); s4 = s4.append(s3, 3, 9); // Append substring of s3 String comparisons Operators ==, !=,, >= (return value bool). Member function compare (return value <0, 0, or >0 as from strcmp). if (s1.compare(s2) == 0) cout << ”Strings are identical”; Comparing substring with overloaded functions if(!s1.compare(2, 5, s2, 10, 5)) { cout << ”Strings s1 and s2 contain same”; cout << ” substring of 5 characters”; cout << ”starting at character position 2”; cout <<” in s1 and character position 10 in s2; }

6 HL5 Substrings, size, length and capacity Taking substrings string s1(”Espoo-Vantaa Institute of Technology”); string s2, s3; s2 = s1.substr(0, 5);//Espoo s3 = s1.substr(13, 9);//Institute Swapping strings string s1(”Espoo”); string s2(”Vantaa”); s1.swap(s2); //s1 contains Vantaa and s2 Espoo Member functions length, size, capacity and max_size length and size return the number of characters of the string currently stored in string. capacity returns the number of characters that can be stored in the string without reallocation max_size returns the absolute upper limit for the size of string in the current environment. Example. string s1; cout << s1.size() << s1.length() << s1.capacity(); s1 = ”abcdef”; cout << s1.size() << s1.length() << s1.capacity(); s1.resize(s1.size() + 5); cout << s1.size() << s1.length() << s1.capacity(); s1.reserve(30); cout << s1.size() << s1.length() << s1.capacity();

7 HL6 Allocation policy As we saw in the previous page, the size (length) of the string can be different from the capacity. The memory allocation policy can be different in different systems but the following example gives an idea of how it could work (this is the case in DevCpp). Example. Size CapacityContents string s; // 00Empty s = “abcd”;// 44|abcd| s.reserve(8);// 48|abcd| s = s + “efg”;// 78|abcdefg| s = s + “hij”;// 1010|abcdefghij| s.resize(14);// 1414|abcdefghij □□□□ | s.reserve(20);// 1420|abcdefghij □□□□ | s.resize(17)// 1720|abcdefghij □□□□□□□ | □ represents a space in the example above

8 HL7 Find and replace Finding substrings and characters 01234567890123456789012345 string s1(”xxcxxxabcxxxxxxxxabcxxxxxx”); int pos; pos = s1.find(”abc”); // 6 (find string “abc”) pos = s1.rfind(”abc”); //17 (reverse find) pos = s1.find_first_of(”abc”);//2 (find one char) pos = s1.find_last_of(”abc”);//19 (reverse find) pos = find_first_not_of(”xac”);//7 (find one char) pos = find_last_not_of(”xac”);//18 (reverse find) The return value of find is string::npos if not found. Replacing substrings and characters string s1(”Espoo-Vantaa Institute of Technology”); s1.erase(5);//Espoo string s2(”xxxxxyyyxxxxxxxxxxx”); s2.replace(5, 3, ”abc”);//xxxxxabcxxxxxxxxxxx s2.replace(5,3, ”abcedfYYYghi”, 6,3); //xxxxxYYYxxxxxxxxxxx Inserting strings string s1(”Espoo Institute of Technology”); string s2(”xxxxxVantaayyyyy”); //s1.insert(5, ”-Vantaa”);//Espoo-Vantaa Institute of.. s1.insert(5, ”-”).insert(6, s2, 5, 6); //--”--

9 HL8 Conversions and iterators Conversions to C-string (member functions copy, data and c_str) copy size_t copy( char *cb, size_t n, size_t pos = 0 ); Function copies from the C++ string to the C character array. You need to add terminating zero yourself. data const char *data() const; c_str const char *c_str() const; String streams In memory I/O. Include files iostream and sstream are needed Classes istringstream and ostringstream Member function str of ostringstream. Connecting buffer or not connecting memory buffer. C++-style or C-style string buffer See example in the following page. Iterators (to be discussed later) class string::const_iterator; string member functions begin and end; iterator comparison operators dereference operator increment operators string::reverse_iterator string::const_reverse_iterator These two functions work in similar way at least in DevCpp

10 HL9 String streams We have used input streams to read information from the keyboard and output streams to display information. Input streams and output stream make conversions as we see in the following example int a = 127; double b; cout << a; // conversion is done from int to chars cin >> b; // conversion is done from chars to double When we write (<<) information to the stream, it goes to the display. When we read (>>) information from the stream it comes from the keyboard. In the lab exercises 5 we saw that we can connect a stream to the disk file. It is also possible to specify a stream that contains a string. In this case when we write data to the stream it goes to the string and when we read the stream, data comes from the string. This is useful when we need to make conversions. See an example program in the following page.

11 HL10 String streams example // This program demonstrates how to use string // streams to make conversions from numbers to // strings and vice versa int main() { // Convert a number to string string num_str; int num_int = 127; ostringstream string_stream; string_stream << num_int; num_str =string_stream.str(); // now we have it // as a string // Convert a string to the number string num_str(“127”); int num_int; istringstream string_stream(num_str); string_stream >> num_int; // now we have it // as int }

Download ppt "Copyright  Hannu Laine C++-programming Part 5 Strings."

Similar presentations

Ads by Google