lec06-string_class

lec06-string_class - CSC 1111 Introduction to Computing...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
1 CSC 1111 Introduction to Computing using C++ Standard class string
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 C-string (or C-style string) Inherited from the C language, a C-string is an array of char . In C++, all string constants are represented as C- strings H e l l o W o r l d '\0' "Hello World" The above string constant is represented as an array of char (a C-string) by the compiler as: 0 1 2 3 4 5 6 7 8 9 10 11 Index
Background image of page 2
3 class string A standard class to represent strings Repackaging of C-strings in C++ as objects Hides the representation of strings from programmer Offers a wide range of methods to "use" string objects Makes manipulating strings easier length() append(…) at(…) compare() substr(…) etc. insert(…) find(…) Programmers manipulate a string object through methods
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
4 #include <iostream> #include <string> // Need to include header "string" using namespace std; int main() { // If not initialized, s1 holds "" (an empty string) string s1; string s2 = "Hello" ; // s2 holds the string "Hello" string s3( "World" ); // s3 holds the string "World" string s4(s3); // s4 holds what s3 is holding cout << s1 << " " << s2 << " " << s3 << " " << s4 << endl; return 0 ; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Hello World World Declaring and initializing string objects
Background image of page 4
5 #include <iostream> #include <string> using namespace std; void foo(string str) { cout << str << endl; } int main() { string s1, s2 = "XYZ" ; s1 = s2; // Copy the value of s2 to s1 s2 = "ABC" ; // "=" has been overloaded for assigning // a string constant to s2 foo(s1); // Pass by value. i.e., copy the value of foo( "DEF" ); // the argument to the parameter as // " parameter = argument" return 0 ; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 XYZ DEF String assignment and passing string objects to function
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
6 String Concatenation Operator " + " and " += " have been overloaded to
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 23

lec06-string_class - CSC 1111 Introduction to Computing...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online