0% found this document useful (0 votes)
114 views41 pages

Module G-Strings: Slots 22 & 23: Theory and Demo. Slot 24: Exercise

The document discusses strings in C programming. It covers declaring and initializing strings, accessing characters in strings, common string functions like input and output, and managing arrays of strings. The key topics are: 1) how strings are stored with a null terminator, 2) declaring static and dynamic strings, 3) common functions for input, output, and other operations on strings, and 4) storing strings in an array.

Uploaded by

Dương Ngân
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views41 pages

Module G-Strings: Slots 22 & 23: Theory and Demo. Slot 24: Exercise

The document discusses strings in C programming. It covers declaring and initializing strings, accessing characters in strings, common string functions like input and output, and managing arrays of strings. The key topics are: 1) how strings are stored with a null terminator, 2) declaring static and dynamic strings, 3) common functions for input, output, and other operations on strings, and 4) storing strings in an array.

Uploaded by

Dương Ngân
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Programming Fundamentals using C

Module G-Strings

Slots 22 & 23: Theory and Demo.


Slot 24: Exercise
Programming Fundamentals using C

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?
Strings 2
Programming Fundamentals using C

Content
• 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

Strings 3
Programming Fundamentals using C

1- 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.

Strings 4
Programming Fundamentals using C

2- 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));

Strings 5
Programming Fundamentals using C
3- Gap:
A safe method for string content.
• Some compilers use a gap between variables
to make a safety for strings. 2293612 10
Safe
gap
28 bytes
Hello
2293584
2293580 9

If a so-long string
is accepted, this
string can
overflow into the
memory of the
variable n
Strings 6
Programming Fundamentals using C

4- 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

Strings 7
Programming Fundamentals using C

5- Output Strings – Test yourself

Observe the
prompt symbol
on the result
screen .

Strings 8
Programming Fundamentals using C

6- Input Strings

• Library: stdio.h
• Function scanf() with type conversion %s
• Function gets(string)
• Each function has it’s own advantages and
weaknesses.

Strings 9
Programming Fundamentals using C

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.

Strings 10
Programming Fundamentals using C

Input Strings: scanf(…)

char name[31];
Default
scanf("%s", name );
Enter: My name is Arnold

char name[31];
scanf(“%10s", name );
Enter: Schwartzenegger

Strings 11
Programming Fundamentals using C

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.

Strings 12
Programming Fundamentals using C

Input Strings: scanf(…)

How to accept blanks in a input string?


%[^\n] conversion specifier.

Strings 13
Programming Fundamentals using C

Input Strings: scanf(…) - Test

Why?
Replace:
Why? scanf(“%s”, S)  scanf(“%10[^\n]”, S)

Strings 14
Programming Fundamentals using C

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

Strings 15
Programming Fundamentals using C

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)

Strings 16
Programming Fundamentals using C

Input Strings: gets(…)

2293612 n1: 10 Overflow


2293608 n2: 33

s
2293584
2293580 12

Strings 17
Programming Fundamentals using C

Input Strings:
Do yourself a function for input s string

Strings 18
Programming Fundamentals using C

7- 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

Strings 19
Programming Fundamentals using C

7- May Operators Applied to String?

• The assign operator can act on pointers to


dynamic array. 4
3
2
1
H 4030000 0
E 13
A 11
P 9
7
5
3
4010000 1

a1 4030000
Stack a2 4010000

Assign Pointer: OK
Strings 20
Programming Fundamentals using C

7- 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.

Strings 21
Programming Fundamentals using C

Others String Functions: string.h

HOA ANH DAOhoa A


2293584 2293596

strstr()  NULL if the substring doesn’t exist.

Strings 22
Programming Fundamentals using C

8- Some User-Defined String Functions

Purpose Prototype
Trim blanks at the beginning of a char* lTrim(char s[])
string: “ Hello”  “Hello”

Trim blanks at the end of a char* rTrim(char s[])


string: “Hello ”  “Hello”

Trim extra blanks in a string: char* trim (char s[])


“ I am a student “
 “I am a student”
Convert a string to a name: char* nameStr( char s[])
“ hoang thi hoa “
 “Hoang Thi Hoa”

Strings 23
Programming Fundamentals using C

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

Strings 24
Programming Fundamentals using C

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

Strings 25
Programming Fundamentals using C

Some user-defined String Functions


“ Hoa anh dao “ “Hoa anh dao“
“Hoa anh dao“
lTrim “Hoa anh dao“
“Hoa anh dao “ “Hoa anh dao“
rTrim “Hoa anh dao“
“Hoa anh dao“ “Hoa anh dao“

Strings 26
Programming Fundamentals using C

Some user-defined String Functions


“ hOA anH dAo nO “
trim()
“hOA anH dAo nO“ h o a a n h d a o n o
strlwr() 0 1 2 3 4 5 6 7 8 9 1 1 1 1
“hoa anh dao no“ 0 1 2 3

“Hoa Anh Dao No“

Strings 27
Programming Fundamentals using C

Some user-defined String Functions

Strings 28
Programming Fundamentals using C

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
i 0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9

count 0 1 2 3 4 5 6

Counting words
Criteria for increasing count:
in a string - s[i] is not a blank and (i==0 or s[i-1] is a blank)

Do Yourself

Strings 29
Programming Fundamentals using C

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 1 1 1 1 1 1 1 1 1
i 0 1 2 3 4 5 6 7 8 9

count 0 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)

Strings 30
Programming Fundamentals using C

Some user-defined String Functions


Replace all existences of a sub-string (subStr) in a string (source) by another (repStr)

source ptr= strstr(source, subStr)


subStr: “coc”, subL=3
repStr: “bo”, repL=2 c o n c o c t r o n g h a n g

strcpy(ptr, ptr+subL)
The function strcpy will c o n t r o n g h a n g
copy char-by-char from
the left to the right of strcpy(temp, ptr)
the source to the t r o n g h a n g
destination. So, it will
work properly when a strcpy(ptr+repL, temp)
sub-string is shifted up c o n t t r o n g h a n g
only.

A temporary string is repStr b o \0


used when a sub-string
for (i=0; i<repL, i++) *(ptr+i) = repStr[i];
is shifted down.
Strings 31
Programming Fundamentals using C

Some user-defined String Functions


Replace all existences of a sub-string (subStr) in a string (source) by another (repStr)

Strings 32
Programming Fundamentals using C

Some user-defined String Functions


Replace all existences of a sub-string (subStr) in a string (source) by another (repStr)

Strings 33
Programming Fundamentals using C

5- Array of Strings
Declaration: char identifier [numberOfString][number_byte_per_string];

Initialization:

Dinh Tien Hoang


Le Dai Hanh
Ly Cong Uan
Le Loi
Tran Nguyen Han
Le Thanh Tong
Nguyen Hue
Strings 34
Programming Fundamentals using C

Array of Strings…
Parameter in a function

Strings 35
Programming Fundamentals using C

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.

Strings 36
Programming Fundamentals using C

Demo: Array of Names

Strings 37
Programming Fundamentals using C

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.
Strings 38
Programming Fundamentals using C

Summary
String Input
– scanf
– gets
– Do yourself using getchar()
String Functions and Arrays of Strings
• Functions
– strlen
– strcpy
– strcmp
– strcat
Q&A
– strstr
• Arrays of Strings
– Input and Output
– Passing to Functions
– Sorting an Array of Names

Strings 39
Programming Fundamentals using C

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 40
Programming Fundamentals using C

Thank You

Strings 41

You might also like