{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

More Things about Strings

More Things about Strings - More Things about Strings A...

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

View Full Document Right Arrow Icon
More Things about Strings A string is a sequence of zero or more characters. The size function tells you how many characters are in the string: string s = "Hello"; cout << s.size(); // writes 5 s = "Wow"; cout << s.size(); // writes 3 s = ""; cout << s.size(); // writes 0 (For historical reasons, there is also a length function that returns the same value that size does. In other words, s.length() and s.size() may be used interchangeably.) You can access individual characters in a string using the at funtion. The positions of the characters in a string are numbered from left to right, starting at 0. Your program will be terminated if it tries to access a character at a position that is out of range for the string. // 01234 string s = "Hello"; // Hello cout << s.at(0); // writes H cout << s.at(4); // writes o cout << s.at(5); // This would terminate the program. cout << s.at(-1); // This would terminate the program. To visit every character in a string (for example, to write each character of the string on a line by itself), you can say string s = "Hello"; for (int k = 0; k != s.size(); k++) cout << s.at(k) << endl; While this will work for everything you're doing in this class, technically the expression s.size() returns a number of a special type defined in the library: not int , but string::size_type . This type name is a synonym for some unsigned integer type. (An unsigned integer variable
Background image of page 1

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

View Full Document Right Arrow Icon
can contain only whole numbers, no negatives.) It turns out that a
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}