FP - Topic 6 - String
FP - Topic 6 - String
Fundamentals of Programming
String
Rev.240901
HCM City 1
String in C/C++
• C++ provides two types of string representations:
– The C-style character string (C-String)
– The string class type introduced with Standard C++.
2
Content
• C-style string
• String class
• Exercise
3
C-String
• The C-String originated within the C language
and continues to be supported within C++.
– String is nothing but an array of characters.
– Every string is terminated with '\0' (NULL)
character.
▪ A character array which is not null terminated is not a
valid C string.
▪ Null character marks the end of the string, it is the only
way for the compiler to know where this string is
ending.
4
Examples
“PROGRAM”
“c string tutorial”
5
Notes
• Note:
C-String length = array size – 1
• Example
6
Declaration and Initialization
• A string can be declared as a character array or
with a string pointer.
7
Example
8
Example
9
Note
• Initialize an array of characters at the moment it is being declared, and
not about assigning values to them later (once they have already been
declared).
– Because string literals are regular arrays, they have the same restrictions as these,
and cannot be assigned values.
10
Input and output for C-Strings
• Use the scanf() function to read a string and printf()
function to print a string like any other data types.
int scanf ( const char * format, ... );
int printf ( const char * format, ... );
– The scanf() function only takes the first entered word.
▪ The function terminates when it encounters a white space (or just space).
11
Example
12
Input and output for C-Strings (cont)
13
Quiz
• What will be the output of the following
code?
14
Quiz
• What will be the output of the following
code?
15
Input string with space
• Using gets() and puts()
– gets() function can get string to newline character.
– However, the most recent revision of the C standard (2011) has
definitively removed this function from its specification because it
not safe.
16
Input string with space
17
Input string with space
• Use the fgets function or cin.getline
– Receive characters from the keyboard until they
encounter a carriage return.
– The string received is what the user entered (except for
a carriage return).
char course[50];
printf(“Enter string: ”);
fgets(course, 50, stdin);//cin.getline(course,50)
printf(“Input string is: %s”, course);
Enter string: Intro to Programming
Input string is: Intro to Programming
18
Passing C-Strings to Functions
• C-Strings are just char arrays. So, they can be passed to a
function in a similar manner as arrays.
20
Library for manipulating string
22
Copy the string
Pointer dest.
char s[100];
s = “Visual C++ 6.0”; // error
strcpy(s, “Visual C++ 6.0”); // correct
23
Create duplicate string
char *s;
s = strdup(“Visual C++ 6.0”);
24
Convert string to lower case
pointer to s.
25
Convert string to upper case
pointer to s.
26
Reverse the string
27
Compare two strings (sensitive)
< 0 if s1 < s2
== 0 if s1 == s2
>0 if s1 > s2
28
Compare two strings (insensitive)
< 0 if s1 < s2
== 0 if s1 == s2
>0 if s1 > s2
29
Concatenate two strings
30
Find the substring in the string
31
Quiz
• What will be the output of the following
code?
32
Content
• C-style string
• String class
• Exercise
33
C++ String class
• C++ provides a String class, you can also create a
objects of string class for holding strings.
– Large body of member functions
– Overloaded operators to simplify expressions
• To use C++ String Class, provide the appropriate
#include directive:
34
Features
• string features
– Not null terminated
– string not a pointer
– Many member functions take start position and
length
▪ If length argument too large, max chosen
35
Example
• The following instructions are all equivalent.
36
Notes
• No conversion from int or char
– The following definitions are errors
▪ string error1 = 'c';
▪ string error2( 'u' );
▪ string error3 = 22;
▪ string error4( 8 );
– However, can assign to one char if declared
▪ string s;
s = 'n';
s = 65;
37
Input and output
• Use insertion << and extraction >> operators
– Input delimited by white-space characters
• getline(cin, str) for reading a string and including
white spaces
– Note that cin >> str; will NOT get the whole line, but only
ONE word right before the space
– Input delimited by a newline ('\n‘)
38
Example
39
string Operators
Operator Meaning
= Assignment
+ Concatenation
+= Concatenation assignment
== Equality
!= Inequality
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
>> Reads
<< Prints
40
Examples
• str2 = str1; // assigning a string
• str3 = str1 + str2; //concatenating strings
• if(str2 > str1) cout<<” str2 is bin“;//compares
• str1 = "This is a null-terminated string.\n";
• cin>>str1; //reads
• cout<<str1; //prints
41
More powerful
• Concatenation of Mixed-Style Strings.
For example, s = u + v + w, where s is of type
string, u can be:
– A string object, or
– a C-style string (a char array or a char pointer),
– a C-style char
– or a double-quoted string,
– or a single-quoted character.
However, at least u or v or w must be a string
object
42
Example
43
Example of string Comparisons
44
Index Operator []
• If x is a string object, and you wish to obtain the
value of the k-th character in the string, you write:
x[k];
• This feature makes string objects appear like
arrays of chars.
45
string operations
46
string operations
47
string operations
48
Example
49
Quiz
• What will be the output of the following
code?
50
Quiz
• What will be the output of the following
code?
51
Converting between std::string and C-style Strings
52
Content
• C-style string
• String class
• Exercise
53
Exercises
• Exercise 1: read some other functions
– atoi, atol, atof : convert string to number (stdlib.h)
– itoa, ltoa, ultoa: convert numbers to strings.
– strtok
• Exercise 2: Write a function that takes a string
and returns the corresponding string (keeping
the input string unchanged):
– Convert characters to lowercase (like strlwr).
– Convert characters to uppercase (like strupr).
– Change the first characters of each word to an
uppercase letter.
– Remove leading and trailing spaces in string.
54
Exercises
• Exercise 3: Write a function that receive a string s
and returns the corresponding string after removing
spaces.
• Exercise 4: Write a function that receive a string s
and counts how many words in that string.
• Exercise 5: Write a function that receive a string s
and outputs words on consecutive lines.
• Exercise 6: Write a function to find the word with the
largest length and output it to the screen and its
length respectively.
• Exercise 7: Write a function that extracts the first /
last n characters the given string s.
55
The End