2. Objectives
• String is a common-used data type
→ The way is used to store a string
of characters in C.
• How to declare/initialize a string in
C?
• How to access a character in a
string?
• What are operations on strings
• Input/output (stdio.h)
• Some common used functions in
the library string.h
• How to manage an array of
strings?
3. Contents • Null-String/C-String
• To Declare/Initialize a
string
• Gap: A safe method for
string content.
• Data stored in a string
• Output a String
• Input a string
• May Operators Applied to
String?
• Other String Functions
• Array of strings
3
4. Null-String/ C-String
• A string is a group of characters → It is similar to an array of
characters.
• A NULL byte (value of 0 – escape sequence ‘0’) is inserted to
the end of a string. → It is called NULL-string or C-string.
• A string is similar to an array of characters. The difference
between them is at the end of a string, a NULL byte is
inserted to locate the last meaningful element in a string.
➔ If a string with the length n is needed, declare it with the
length n+1.
4
Strings
5. Declare/ Initialize a String
• Static strings: stored in data segment or stack segment →
Compiler can determine the location for storing strings.
char s1[21]; /* for a string of 20 characters*/
Initialize a string: NULL byte is automatically inserted.
char name[31] = “I am a student”;
char name2[31] = {‘H’, ‘e ‘, ‘l’, ‘l’, ‘o’, ‘0’ };
• Dynamic strings: Stored in the heap
char* S;
S = (char*) malloc( lengthOfString+1);
S = (char*) calloc( lengthOfString+1, sizeof(char));
5
Strings
6. Gap: A safe method for string content.
• Some compilers use a gap between variables to make a
safety for strings.
2293612 10
2293580 9
2293584
28 bytes
Hello
Safe
gap
If a so-long string
is accepted, this
string can
overflow into the
memory of the
variable n
6
Strings
7. Data Stored in a strings
• Each character in a string is stored as it’s ASCII code.
S1[i]: The character at
the position i in the
string S1
7
Strings
8. Output Strings – Test yourself
Observe the
prompt symbol
on the result
screen .
8
Strings
9. Input Strings
• Library: stdio.h
• Function scanf() with type conversion %s
• Function gets(string)
• Each function has it’s own advantages and weaknesses.
9
Strings
10. Input Strings: scanf(…)
The %s conversion specifier
• reads all characters until the first whitespace character,
• stores the characters read in memory locations starting with
the address passed to scanf,
• Automatically stores the null byte in the memory byte
following the last character accepted and
• leaves the delimiting whitespace plus any subsequent
characters in the input buffer → ignores any leading
whitespace characters (default).
• Option specifiers are used to change default characteristics
of the function scanf on strings.
10
Strings
11. Input Strings: scanf(…)
char name[31];
scanf("%s", name );
Enter: My name is Arnold
char name[31];
scanf(“%10s", name );
Enter: Schwartzenegger
Default
11
Strings
12. Input Strings: scanf(…)
How to accept blanks in a input string?
➔%[^n] conversion specifier
• reads all characters until the newline ('n'),
• stores the characters read in memory locations
starting with the address passed to scanf,
• stores the null byte in the byte following that where
scanf stored the last character and
• leaves the delimiting character (here, 'n') in the input
buffer.
12
Strings
15. Input Strings: scanf(…)
Some character specifiers used in the function scanf(): Set of
character are or not accepted.
Specifier Description
%[abcd] Searches the input field for any of the characters a, b, c,
and d
%[^abcd] Searches the input field for any characters except a, b, c,
and d
%[0-9] To catch all decimal digits
%[A-Z] Catches all uppercase letters
%[0-9A-Za-z] Catches all decimal digits and all letters
%[A-FT-Z] Catches all uppercase letters from A to F and from T to Z
15
Strings
16. Input Strings: gets(…)
gets is a standard library function (stdio.h) that
• accepts an empty string
• uses the 'n' as the delimiter
• throws away the delimiter after accepting the string
• Automatically appends the null byte to the end of the
set stored
The prototype for gets is
char* gets(char [ ]);
(gets is dangerous. It can fill beyond the
memory that allocated for the string)
16
Strings
19. May Operators Applied to String?
• C operators act on basic data type only.
➔ They can not be applied to static arrays and static strings.
We need functions for processing
arrays and string
19
Strings
20. May Operators Applied to String?
• The assign operator can act on pointers to dynamic array.
1
3
5
7
9
0
1
2
3
4
11
13
4030000
4010000
4030000
4010000
a1
a2
H
E
A
P
Stack
Assign Pointer: OK
20
Strings
21. Others String Functions: string.h
Purpose Function
Get the length of a string int strlen (char s[])
Copy source string to destination string char* strcpy(char dest[], char src[])
Compare two strings int strcmp( char s1[], char s2[]) → -1, 0, 1
Concatenate string src to the end of dest char* strcat(char dest[], char src[])
Convert a string to uppercase char* strupr(char s[])
Convert a string to lowercase char* strlwr(char s[])
Find the address of a substring char* strstr (char src[], char subStr[])
→ NULL if subStr does not exist in the src.
21
Strings
22. Others String Functions: string.h
HOA ANH DAOhoa A
2293584 2293596
strstr() → NULL if the substring doesn’t exist.
22
Strings
23. Some User-Defined String Functions
Purpose Prototype
Trim blanks at the beginning of a string:
“ Hello” → “Hello”
char* lTrim(char s[])
Trim blanks at the end of a string: “Hello
” → “Hello”
char* rTrim(char s[])
Trim extra blanks ins a string:
“ I am student “
→ “I am a student”
char* trim (char s[])
Convert a string to a name:
“ hoang thi hoa “
→ “Hoang Thi Hoa”
char* nameStr( char s[])
23
Strings
24. Some user-defined String Functions
0 1 2 3 4 5 6
H o a NULL
i=0 1 2 3
0 1 2 3 4 5 6
H o a NULL o a NULL
24
Strings
25. Some user-defined String Functions
0 1 2 3 4 5 6
H o a NULL
2 3 4 i=5
0 1 2 3 4 5 6
H o a NULL NULL
25
Strings
26. Some user-defined String Functions
“ Hoa anh dao “
“Hoa anh dao “
“Hoa anh dao“
lTrim
rTrim
“Hoa anh dao“
“Hoa anh dao“
“Hoa anh dao“
“Hoa anh dao“
“Hoa anh dao“
“Hoa anh dao“
26
Strings
27. Some user-defined String Functions
“ hOA anH dAo nO “
“hOA anH dAo nO“
“hoa anh dao no“
“Hoa Anh Dao No“
h o a a n h d a o n o
0 1 2 3 4 5 6 7 8 9 1
0
1
1
1
2
1
3
27
Strings
trim()
strlwr()
29. Some user-defined String Functions
Suppose that only the blank character is used to separate words in a sentence.
Implement a function for counting number of words in a sentence.
T n u n a n u n o n g t
0 1 2 3 4 5 6 7 8 9 1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
count 0
i
1 2 3 4 5 6
Counting words
in a string
Do Yourself
29
Strings
Criteria for increasing count:
- s[i] is not a blank and (i==0 or s[i-1] is a blank)
32. Some user-defined String Functions
Counting integers in a string
1 2 n u a 7 n a 9 d f 1 2 3 4 5 9 P 7
0 1 2 3 4 5 6 7 8 9 1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
count 0
i
1 2 3 4 5
Do Yourself Criteria for increasing count:
- s[i] is a digit and (i==0 or s[i-1] is
not a digit)
35. Some user-defined String Functions
Replace all existences of a sub-string (subStr) in a string (source) by another (repStr)
c o n c o c t r o n g h a n g
35
Strings
source
subStr: “coc”, subL=3
repStr: “bo”, repL=2
ptr= strstr(source, subStr)
c o n t r o n g h a n g
strcpy(ptr, ptr+subL)
t r o n g h a n g
strcpy(temp, ptr)
c o n t t r o n g h a n g
strcpy(ptr+repL, temp)
b o 0
for (i=0; i<repL, i++) *(ptr+i) = repStr[i];
The function strcpy will
copy char-by-char from
the left to the right of
the source to the
destination. So, it will
work properly when a
sub-string is shifted up
only.
A temporary string is
used when a sub-string
is shifted down.
repStr
36. Some user-defined String Functions
36
Strings
Replace all existences of a sub-string (subStr) in a string (source) by another (repStr)
37. Some user-defined String Functions
37
Strings
Replace all existences of a sub-string (subStr) in a string (source) by another (repStr)
38. Array of Strings
Dinh Tien Hoang
Le Dai Hanh
Ly Cong Uan
Le Loi
Tran Nguyen Han
Le Thanh Tong
Nguyen Hue
Declaration: char identifier [numberOfString][number_byte_per_string];
Initialization:
40. Demo: Array of Names
Write a C program that will accept 10 names, print out the list,
sort the list using ascending order, print out the result.
40
Strings
42. Summary
• String in C is terminated by the NULL character (‘0’)
• A string is similar to an array of characters.
• All input functions for string will automatically add the NULL
character after the content of the string.
• C-operators will operate on simple data types ➔ Function on
arrays, strings are implemented to operate on arrays and
strings
• If dynamic arrays or strings (using pointers), the assignment
can be used on these pointers.
42
Strings
43. Summary
String Input
• scanf
• gets
• Do yourself using getchar()
String Functions and Arrays of Strings
• Functions
• strlen
• strcpy
• strcmp
• strcat
• strstr
• Arrays of Strings
• Input and Output
• Passing to Functions
• Sorting an Array of Names
Q&A
43
Strings
44. Slot 24- Exercise
Write a C-program that helps user managing a list of 100
student names using the following menu:
1- Add a student
2- Remove a student
3- Search a student
4- Print the list in ascending order
5- Quit
Strings 44