Chapter 9
Strings
Copyright © 2017 Pearson Education, Ltd.
All rights reserved.
Introduction
• Two string types: C-strings and String class
• C-strings : Array with base type char, inherited from C
– Typically "partially-filled" array
– One character per indexed variable
– One extra character: "\0“ that is the end of string marked with null
– Literal "Hello" stored as c-string
– Declaration: does not require C++ library: Built into standard C++
– Manipulations: Require library <cstring>, typically included when using c-
strings.
char myStr[10]; // myStr can hold up to 9 characters + one null character
char s[10]= "Hi Mom"; // initialize c-string and places "\0" at end
9-2
C-String Indexes
• Can omit array-size: char shortString[] = "abc";
– Automatically makes size one more than length of quoted string
– Places '\0' in the array after the characters 'a' , 'b' , and 'c'
– NOT same as: char shortString[] = {"a", "b", "c"};
• Does not put a '\0' anyplace in the array
• Can access indexed variables of: Char s[5] = "DoB";
– s[0] is “D“, s[1] is “o“, s[2] is “B”, s[3] is "\0“, s[4] is unknown
• Can manipulate indexed variables such as s[3] = "Z";
– Be careful here, "\0" (null) was overwritten by a "Z"!
• c-string no longer "acts" like c-string!: Unpredictable results!
char ourString[5] = "Hi";
int index = 0;
while (ourString[index] != "\0")
{
ourString[index] = "X";
index++;
9-3
}
C-String predefined functions
• C-strings not like other variables: cannot assig or compare with = and ==
– Must use <cstring>library function
char s[10];
s = "Hello";//ILLEGAL! Can ONLY use "=" at declaration of c-string
strcpy(s, "Hello"); //Sets value of s equal to "Hello"
char s1[10] = "Hello";
char s210] = "Goodbye";
If (s1 == s2) // NOT allowed!
if (strcmp(s1, s2))
cout << "Strings NOT same.";
else
cout << "Strings are same.";
– strcpy(aStrin, "Hello"); //does not check for size! Up to programmer
char myString[20] = "dobedo";
cout << strlen(myString); // result here is 6
char stringVar[20] = "The rain";
strcat(myString, "in Spain"); //myString now contains " dobedoin Spain"
– strlen() : "String length“, returns number of characters, not including null.
– strcat(): "String concatenate": be careful, incorporate spaces as needed!
9-4
Some
Predefined
C-String
Functions
in
<cstring>
9-5
C-String Output & input
• Can output with insertion operator, <<
• As we’ve been doing already: cout << news << " Wow.\n";
– Where news is a c-string variable
• Possible because << operator is overloaded for c-strings!
• Can input with extraction operator, >>
– Input reading "stops" at delimiter
• Whitespace is "delimiter"
– Watch size of c-string: Must be large enough to hold entered string!
• C++ gives no warnings of such issues!
char a[80], b[80];
Enter input: Do be do to you! cout << "Enter input: ";
DobeEND OF OUTPUT cin >> a >> b;
cout << a << b << "END OFOUTPUT\n";
• C-string a receives: "do"
• C-string b receives: "be"
9-6
C-String Line Input with getline()
• C-String Line Input: receive entire line into c-string
• Use getline(), a predefined member function:
char a[80]; Enter input: Do be do to you!
cout << "Enter input: "; Do be do to you!END OF INPUT
cin.getline(a, 80);
cout << a << "END OF OUTPUT\
n";
• getline() can explicitly tell length to receive:
char s[5]; Enter input: dobedowap
cout << "Enter input: "; dobeEND OF OUTPUT
cin.getline(s, 5);
cout << s << "END OF OUTPUT\n";
• Forces FOUR characters only be read (recall need for null character!)
• C-string Arguments: c-string parameter is array parameter
– C-strings passed to functions can be changed by receiving function!
– Like all arrays, typical to send size as well or "could" use "\0" to find end
9-7
Example: Command Line Arguments
• Programs invoked from the command line can be sent arguments
• Header for main: int main(int argc, char *argv[])
– argc specifies how many arguments are supplied. The name of the program
counts, so argc will be at least 1.
– argv is an array of C-Strings.
• argv[0] holds the name of the program that is invoked
• argv[1] holds the name of the first parameter
• argv[2] holds the name of the second parameter
• Etc.
// Echo back the input arguments
int main(int argc, char *argv[]){
for (int i=0; i<argc; i++){
cout << "Argument " << i << " " << argv[i] << endl;
}
return 0; Sample Execution
}
Sample Execution > Test hello world
Invoking Test
Argument 0 Test
> Test from command Argument 1 hello
Argument 0 Test prompt Argument 2 world
Character I/O
• Input and output data: all treated as character data
– e.g., number 10 outputted as "1" and "0"
– Conversion done automatically
• Uses low-level utilities
• Can use same low-level utilities ourselves as well
• get() : Member function of cin object that reads one char at a
time
char nextSymbol;
cin.get(nextSymbol);
– Reads next char & puts in variable nextSymbol
– Argument must be char type NOT "string"!
• put():Member function of cout object that outputs one char at a
time
cout.put("a"); // Outputs letter "a" to screen
char myString[10] = "Hello";
cout.put(myString[1]); //Outputs letter "e" to screen 9-9
Character-Manipulating Functions: in <cctype>
9-10
Character-Manipulating Functions: in <cctype>
Copyright © 2017 Pearson Education, Ltd. All rights reserved. 9-11
Standard Class string
• Defined in library: #include <string>
using namespace std;
• String variables and expressions treated much like simple types
• Can assign, compare, add: string s1, s2, s3;
s3 = s1 + s2; //Concatenation
s3 = "Hello Mom!" //Assignment
9-12
I/O and getline() with Class string
string s1, s2; • If user types in:
cin >> s1; May the hair on your toes grow long and curly!
cin >> s2; • s1 receives value "May“ and s2 receives value "the"
• For complete lines: Similar to c-string’s usage of getline()
string line;
cout << "Enter a line of input: "; Enter a line of input: Do be do to you!
getline(cin, line); Do be do to you!END OF INPUT
cout << line << "END OF OUTPUT";
• Can specify "delimiter" character:
string line;
cout << "Enter input: ";
getline(cin, line, "?"); //Receives input until "?" encountered
• getline() actually returns reference
string s1, s2;
getline(cin, s1) >> s2;
– Results in: (cin) >> s2;
9-13
Mixing Input Methods and type conversion
int n;
• Be careful mixing cin >> var and getline string line;
– If input is: 42 cin >> n;
Hello hitchhiker. getline(cin, line);
• Variable n set to 42
• line set to empty string!
– cin >> n skipped leading whitespace, leaving "\n" on stream for getline()!
• C-string and string Object Conversions
– from c-string to string object : automatic type conversions
char aCString[] = "My C-string";
string stringVar;
stringVar = aCstring; //Perfectly legal and appropriate!
– from string to c-string object: must use explicit conversion
aCString = stringVar; // ILLEGAL!
strcpy(aCString, stringVar.c_str()); //legal
9-14
Member Functions of Standard Class string (1)
Copyright © 2017 Pearson Education, Ltd. All rights reserved. 9-15
Member Functions of Standard Class string (2)
Copyright © 2017 Pearson Education, Ltd. All rights reserved. 9-16