90 likes | 222 Views
Engineering 1020. Introduction to Programming Peter King peter.king@mun.ca www.engr.mun.ca/~peter Winter 2010. ENGI 1020: Strings. We can store text in a special container called a String String types are special, they are a class, not simple data types
E N D
Engineering 1020 Introduction to Programming Peter King peter.king@mun.ca www.engr.mun.ca/~peter Winter 2010
ENGI 1020: Strings We can store text in a special container called a String String types are special, they are a class, not simple data types Declaring a String makes an object, not just a variable
ENGI 1020: Strings String objects are very similar to variables Declaration string someText; string s = “Programming is fun.” ; Output cout << s << endl;
ENGI 1020: Strings Classes off more power than a data type Main difference is they can encapsulate functions that operate on the data stored in the object we can use the object label and the 'dot' operator to perform operations on the string
ENGI 1020: Strings Example string myName = “Peter”; cout << “my name has “; cout << myName.length() << “letters,”; myName.erase(4,1); cout << “ some people call me “; cout << myName << endl;
ENGI 1020: Strings String functions length - returns the number of characters at - return character at a certain position find - returns the position of a certain character insert - inserts a new character into the string erase - removes a character from a string substr - returns a portion of the string
ENGI 1020: Strings We can use the 'getline' function getline takes a stream and a string by reference string s; getline(cin, s); This will fill s with the input provided by the user, ending when the user hits the Enter key
ENGI 1020: Strings Since many strings will contain spaces, how can we input strings from the user into 1 variable? (remember, cin splits input by space into separate variables)
ENGI 1020: String Coding example A user will enter 3 names (first last) and the program will generate a list of names in the format: last, 1st initial