lec13-string
lec13-string
Fundamental Computing
with C++
Characters and Strings
Fall, 2024
Characters
• A character (a char-type value) is represented
internally as an 8-bit integer that corresponds to
the ASCII code of the character
• ASCII: American Standard Code for Information
Interchange
• E.g., 'A' is 65, '1' is 49, 'a' is 97, ' ' is 32, …
• See next page for the ASCII code of each character
1. As null-terminated strings
• A null-terminated string (also called c-string) is an array
of char (i.e., “char []”, or “char *”)
• The end of the string is indicated by a null character
('\0', ASCII value 0) in the array
2. As string objects
10
Null-terminated Strings (c-strings)
• Inherited from the C Language
s2 a b c d \0
e f g h i j \0
12
(Optional)
Processing C-Strings
• You can process a c-string as if it is an array
13
(Optional)
… …
14
(Optional)
<cstring> Example
1 #include <cstring>
2 #include <iostream>
3 using namespace std;
4
5 int main() {
6 char s1[10], s2[10] = "abc";
7
8 cout << strlen(s2) << endl; // Print 3
9
10 strcpy(s1, s2); // s1 becomes "abc"
11 cout << s1 << endl;
12
13 strcat(s1, "def"); // s1 becomes "abcdef"
14 cout << s1 << endl;
15 3
16 return 0; abc
17 } abcdef 15
Class string
• Hides the actual representation of a string from the
programmers
• Offers many member functions for manipulating
strings
• Makes manipulating strings and managing storage for
strings easier than using arrays
Programmers
length() append(…) at(…) compare(…)
manipulate a
substr(…) insert(…) find(…) … string object
H E L L O ˽ W O R L D \0 through public
0 1 2 3 4 5 6 7 8 9 10 11 member functions
16
Declaring and Initializing string
Objects Using Constructors
1 #include <iostream>
2 #include <string> // Need to include header <string>
3 using namespace std;
4 Remember to add this!
5 int main() {
6 // If not initialized, holds the empty string ""
7 string s1;
8
9 string s2("Hello"); // s2 holds the string "Hello"
10
11 string s3(s2); // s3 holds what s2 is holding
12
13 cout << s1 << "_" << s2 << "_" << s3 << endl;
14
15 return 0;
16 }
_Hello_Hello 17
Some Constructors of string
1. string();
Simply treat it as
2. string( const string &str ); unsigned long
3. string( size_t n, char c );
4. string( const char *str );
5. string( const char *str, size_t n );
1 string str1( 5, 'c' ); // 3
2 string str2( "Now is the time..." ); // 4
3 string str3( "Now is the time...", 8 ); // 5
4 cout << str1 << endl;
ccccc
5 cout << str2 << endl;
Now is the time...
6 cout << str3 << endl;
Now is t
Reference: https://cplusplus.com/reference/string/string/string/ 18
String Assignment and Passing
string Objects to Function
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 void foo(string str) {
6 cout << str << endl;
7 }
8
9 int main() { Copy the content of s2 to s1
10 string s1, s2("XYZ");
11 Use operator = to copy a
12 s1 = s2; c-string to a string object
13 s2 = "ABC";
14
15 foo(s1);
Pass-by-value: copy from the
16 foo("DEF"); argument to the parameter as
17 return 0; “parameter = argument;” XYZ
18 } DEF 19
String Concatenation
• Operators + and += are overloaded for string objects
to support string concatenation
24
Accessing Individual Characters:
Array Subscript Notation
string str("Hello World");
H e l l o ˽ W o r l d
Index 0 1 2 3 4 5 6 7 8 9 10
• Operator [] is overloaded to provide alternative
style for accessing individual characters
• E.g.:
string str("Hello World");
str[i] is equivalent
int len = (int)str.length(); to str.at(i) if i is
str[4] = 'h'; in proper range
cout << str[len - 3];
27
String Input Using Function
getline()
• Read a string from an input stream object until a
newline character is encountered
• The new line character is consumed from the input
stream but is not included in the string object
30
Strings are Compared
Lexicographically
s1 A B C D
s2 A B C X Y
31
String Comparison: Examples
1 string s1("ABC"), s2("XYZ");
2
3 // Print 0 or 1?
4 cout << (s1 > s2) << endl;
5
6 // Print 0 or 1?
7 cout << (s1 == "ABC") << endl;
8
9 // Print 0 or 1?
10 cout << (s1 + "XYZ" == "ABC" + s2) << endl;
11
12 // Improper comparison. Why?
13 if ("ABC" < "ABCD") {
14 …
15 }
32
String Comparison: Exercises
string s1(…) string s2(…) >, ==, or <?
"ABC" "ABCDE"
"XYZ" "abc"
"AB C" "ABC"
"" "ABC"
"13145" "013145"
34
(Optional)
find(): Example
• find(): returns the starting position of the
located substring, or returns -1 if the target string
cannot be found
1 string s1("01234 0123");
2 size_t pos; // size_t is simply unsigned int
3
4 // Locate "123" in s1 starting from position 0
5 pos = s1.find("123"); // pos gets 1
6
7 // Locate "123" in s1 starting from position 2
8 pos = s1.find("123", 2); // pos gets 7
9
10 // Check if a substring exists in a string
11 if (s1.find("ABC") == -1) {
12 … // "ABC" does not exist in s1
13 } 36
substr() and c_str(): (Optional)
Examples
• substr(): returns a “substring” (a portion of a
string) from one position to another position
• c_str(): returns an equivalent c-string from a
string object
1 string s1, s2("0123456789");
2 char *s3;
3
4 /* A substring that starts at position 2 and includes 4
5 characters */
6 s1 = s2.substr(2, 4); // s1 becomes "2345"
7
8 /* A substring that starts at position 4 and includes up to
9 the last character */
10 s1 = s2.substr(4); // s1 becomes "456789"
11
12 s3 = s1.c_str(); // s3 is c-string equivalent to s1 37
(Optional)
insert(): Example
1 string s1, s2("XYZ");
2
3 s1 = "012345";
4 // Insert s2 at position 2 of s1
5 s1.insert(2, s2); // s1 becomes "01XYZ2345"
6
7 s1 = "012345";
8 // Insert "ABC" at position 0 of s1
9 s1.insert(0, "ABC"); // s1 becomes "ABC012345"
10
11 s1 = "012345";
12 s2 = "ABCDEF";
13 /* Insert "BCDE" at position 3 of s1. The 3rd parameter, 1,
14 indicates the start of the substring in s2. The 4th
15 parameter, 4, is the length of the substring in s2 */
16 s1.insert(3, s2, 1, 4); // s1 becomes "012BCDE345" 38
(Optional)
Command-Line Arguments
• Command-line arguments allow users to pass data
to a program from the OS at run-time
Command-line arguments
Program name
Command-Line Arguments
• Command-line arguments are stored as an array of
c-strings in C++
Have to modify the int argc: number of
main() function header command-line arguments
1 #include <iostream>
2 using namespace std;
char-pointers
3 (c-strings)
4 int main(int argc, char *argv[]) {
5 cout << "Num of command-line arg: " << argc << endl;
6 for (int i = 0; i < argc; i++) {
7 cout << "Arg #" << i << ": " << argv[i] << endl;
8 }
9 return 0; Array of char-pointers
10 } (Array of c-strings) 41
(Optional)
Parsing Command-Line Index argv
0 “example.exe”
Arguments 1 “ab”
1 #include <iostream> 2 “cdef”
2 using namespace std; 3 “123”
3 4 “@#$%”
4 int main(int argc, char *argv[]) {
5 cout << "Num of command-line arg: " << argc << endl;
6 for (int i = 0; i < argc; i++) {
7 cout << "Arg #" << i << ": " << argv[i] << endl;
8 }
9 return 0;
10 }
43