0% found this document useful (0 votes)
9 views

FP - Topic 6 - String

Bài 6 - Cơ sở lập trình trường Đại học Khoa Học Tự Nhiên
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

FP - Topic 6 - String

Bài 6 - Cơ sở lập trình trường Đại học Khoa Học Tự Nhiên
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

University of Science, VNU-HCM

Faculty of Information Technology

Fundamentals of Programming

String

Lecturer: Le Ngoc Thanh


Email: [email protected]

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

char fullname[30];// 29 characters long


char datetime[9]; // 8 characters long

6
Declaration and Initialization
• A string can be declared as a character array or
with a string pointer.

char *greeting = “Hello” ;

7
Example

Note: %s is used to print a string

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)

• Can use cin and cout for IO C-String


– cin read and stop when it encounters a whitespace or
newline character, then automatically add the null
character '\0' at the end of the string.
– cout print all characters in the array until it encounters
the null character '\0’.

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

• Using getchar() to read a character

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

• C-Strings handling functions are defined


under "string.h" or <cstring> header file.
– strlen
– strcpy
– strdup
– strlwr/strupr
– strrev
– strcmp/stricmp
– strcat
– strstr
21
Determines the string length

size_t strlen(const char *s)

Determines the string length s.


size_t instead of unsigned (in <stddef.h>)
used to measure unsigned quantities.

String length s (does not include ending


character)

char s[] = “Visual C++ 6.0”;


int len = strlen(s); // => 14

22
Copy the string

char *strcpy(char *dest, const char *src)

Copy string src to string dest, stop when


reach to ‘\0’.
! dest must be large enough to contain src

Pointer dest.

char s[100];
s = “Visual C++ 6.0”; // error
strcpy(s, “Visual C++ 6.0”); // correct

23
Create duplicate string

char *strdup(const char *s)

Create a duplicate of a given string s. The


function will create a memory with strlen (s) + 1
bytes to hold the string s. Manually destroy this
memory when not in use.

Success: return the pointer to the memory


containing the duplicated string.
Fail: return NULL.

char *s;
s = strdup(“Visual C++ 6.0”);

24
Convert string to lower case

char *strlwr(char *s)

Convert the string s to lower case (‘A’ to ‘a’,


‘B’ to ‘b’,…, ‘Z’ to ‘z’)

pointer to s.

char s[] = “Visual C++ 6.0”;


strlwr(s);
puts(s); // visual c++ 6.0

25
Convert string to upper case

char *strupr(char *s)

Convert the string s to lower case (‘a’ to ‘A’,


‘b’ to ‘B’,…, ‘z’ to ‘Z’)

pointer to s.

char s[] = “Visual C++ 6.0”;


strupr(s);
puts(s); // VISUAL C++ 6.0

26
Reverse the string

char *strrev(char *s)

Reverses the order of the characters in the


string s (except the terminating character).

The pointer to the result string.

char s[] = “Visual C++ 6.0”;


strrev(s);
puts(s); // 0.6 ++C lausiV

27
Compare two strings (sensitive)

int strcmp(const char *s1, const char *s2)

Compares the strings s1 and s2 (case


sensitive).

< 0 if s1 < s2
== 0 if s1 == s2
>0 if s1 > s2

char s1[] = “visual C++ 6.0”;


char s2[] = “Visual C++ 6.0”;
int result = strcmp(s1, s2);//=> result > 0

28
Compare two strings (insensitive)

int stricmp(const char *s1, const char *s2)

Compares the strings s1 and s2 (case


insensitive).

< 0 if s1 < s2
== 0 if s1 == s2
>0 if s1 > s2

char s1[] = “visual c++ 6.0”;


char s2[] = “VISUAL C++ 6.0”;
int result = stricmp(s1, s2);// => result = 0

29
Concatenate two strings

char* strcat(char *dest, const char *src)

Concatenate the string src after the string


dest.
!dest must be large enough to contain result

The pointer to the concatenated string.

char s1[100] = “Visual C++”;


char s2[] = “6.0”;
strcat(s1, “ ”); // => “Visual C++ ”
strcat(s1, s2); // => “Visual C++ 6.0”

30
Find the substring in the string

char* strstr(const char *s1, const char *s2)

Find the position of the first occurrence of


s2 in s1

Success: returns the pointer to the first


occurrence of s2 in s1.
Fail: return null.
char s1[] = “Visual C++ 6.0”;
char s2[] = “C++”;
if (strstr(s1, s2) != null)
printf(“Found s2 in s1…”);

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

• Conversion to C-style String:


– To retrieve a C-style string (const char*) from a
std::string, use .c_str().

• Conversion from C-style String to std::string by


assignment operator:

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

You might also like