SlideShare a Scribd company logo
1 of 45
Download to read offline
Module G-Strings
Slots 22 & 23: Theory and Demo.
Slot 24: Exercise
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?
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
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
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
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
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
Output Strings – Test yourself
Observe the
prompt symbol
on the result
screen .
8
Strings
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
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
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
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
Input Strings: scanf(…)
How to accept blanks in a input string?
➔%[^n] conversion specifier.
13
Strings
Input Strings: scanf(…) - Test
Why?
Why? Replace:
scanf(“%s”, S) → scanf(“%10[^n]”, S)
14
Strings
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
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
Input Strings: gets(…)
2293612 n1: 10
2293608 n2: 33
2293584
s
2293580 12
Overflow
17
Strings
Input Strings:
Do yourself a function for input s string
18
Strings
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
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
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
Others String Functions: string.h
HOA ANH DAOhoa A
2293584 2293596
strstr() → NULL if the substring doesn’t exist.
22
Strings
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
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
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
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
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()
Some user-defined String Functions
28
Strings
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)
Counting number of words in a sentence
Counting number of words in a sentence
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)
Counting integers in a string
Counting integers in a string
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
Some user-defined String Functions
36
Strings
Replace all existences of a sub-string (subStr) in a string (source) by another (repStr)
Some user-defined String Functions
37
Strings
Replace all existences of a sub-string (subStr) in a string (source) by another (repStr)
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:
Array of Strings…
Parameter in a function
39
Strings
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
Demo: Array of Names
41
Strings
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
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
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
Please Goto Workshop 07

More Related Content

Similar to 0-Slot21-22-Strings.pdf

Similar to 0-Slot21-22-Strings.pdf (20)

String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
Ch09
Ch09Ch09
Ch09
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
 
Python data handling
Python data handlingPython data handling
Python data handling
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPT
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPT
 
C string
C stringC string
C string
 
string in C
string in Cstring in C
string in C
 
String notes
String notesString notes
String notes
 
Team 1
Team 1Team 1
Team 1
 
strings
stringsstrings
strings
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_
 
Chapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdfChapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdf
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Strings
StringsStrings
Strings
 
String in c programming
String in c programmingString in c programming
String in c programming
 
Operation on string presentation
Operation on string presentationOperation on string presentation
Operation on string presentation
 

More from ssusere19c741

0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdfssusere19c741
 
0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdf0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdfssusere19c741
 
0-Slot13-Programming-With-Menu.pdf
0-Slot13-Programming-With-Menu.pdf0-Slot13-Programming-With-Menu.pdf
0-Slot13-Programming-With-Menu.pdfssusere19c741
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdfssusere19c741
 
0-Slot08-09-10-Module-Functions.pdf
0-Slot08-09-10-Module-Functions.pdf0-Slot08-09-10-Module-Functions.pdf
0-Slot08-09-10-Module-Functions.pdfssusere19c741
 
0-Slot05-06-07-Basic-Logics.pdf
0-Slot05-06-07-Basic-Logics.pdf0-Slot05-06-07-Basic-Logics.pdf
0-Slot05-06-07-Basic-Logics.pdfssusere19c741
 
0-Slot02-Introduction-to-PFC.pdf
0-Slot02-Introduction-to-PFC.pdf0-Slot02-Introduction-to-PFC.pdf
0-Slot02-Introduction-to-PFC.pdfssusere19c741
 
Intro-InstallingTool-FirstProgram
Intro-InstallingTool-FirstProgramIntro-InstallingTool-FirstProgram
Intro-InstallingTool-FirstProgramssusere19c741
 
Background Tasks with Worker Service
Background Tasks with Worker ServiceBackground Tasks with Worker Service
Background Tasks with Worker Servicessusere19c741
 
Real-Time Communication
Real-Time CommunicationReal-Time Communication
Real-Time Communicationssusere19c741
 
Building Websites Using ASP.NET Core Razor Pages
Building Websites Using ASP.NET Core Razor PagesBuilding Websites Using ASP.NET Core Razor Pages
Building Websites Using ASP.NET Core Razor Pagesssusere19c741
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NETssusere19c741
 
Asynchronous and Parallel Programming in .NET
Asynchronous and Parallel Programming in .NETAsynchronous and Parallel Programming in .NET
Asynchronous and Parallel Programming in .NETssusere19c741
 
Networking Programming
Networking ProgrammingNetworking Programming
Networking Programmingssusere19c741
 
Working with XML and JSON Serializing
Working with XML and JSON SerializingWorking with XML and JSON Serializing
Working with XML and JSON Serializingssusere19c741
 
Building Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) ApplicationBuilding Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) Applicationssusere19c741
 
Building Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) ApplicationBuilding Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) Applicationssusere19c741
 

More from ssusere19c741 (19)

0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf
 
0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdf0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdf
 
0-Slot13-Programming-With-Menu.pdf
0-Slot13-Programming-With-Menu.pdf0-Slot13-Programming-With-Menu.pdf
0-Slot13-Programming-With-Menu.pdf
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
 
0-Slot08-09-10-Module-Functions.pdf
0-Slot08-09-10-Module-Functions.pdf0-Slot08-09-10-Module-Functions.pdf
0-Slot08-09-10-Module-Functions.pdf
 
0-Slot05-06-07-Basic-Logics.pdf
0-Slot05-06-07-Basic-Logics.pdf0-Slot05-06-07-Basic-Logics.pdf
0-Slot05-06-07-Basic-Logics.pdf
 
0-Slot02-Introduction-to-PFC.pdf
0-Slot02-Introduction-to-PFC.pdf0-Slot02-Introduction-to-PFC.pdf
0-Slot02-Introduction-to-PFC.pdf
 
Intro-InstallingTool-FirstProgram
Intro-InstallingTool-FirstProgramIntro-InstallingTool-FirstProgram
Intro-InstallingTool-FirstProgram
 
Background Tasks with Worker Service
Background Tasks with Worker ServiceBackground Tasks with Worker Service
Background Tasks with Worker Service
 
Real-Time Communication
Real-Time CommunicationReal-Time Communication
Real-Time Communication
 
Building Websites Using ASP.NET Core Razor Pages
Building Websites Using ASP.NET Core Razor PagesBuilding Websites Using ASP.NET Core Razor Pages
Building Websites Using ASP.NET Core Razor Pages
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NET
 
Asynchronous and Parallel Programming in .NET
Asynchronous and Parallel Programming in .NETAsynchronous and Parallel Programming in .NET
Asynchronous and Parallel Programming in .NET
 
Networking Programming
Networking ProgrammingNetworking Programming
Networking Programming
 
Working with XML and JSON Serializing
Working with XML and JSON SerializingWorking with XML and JSON Serializing
Working with XML and JSON Serializing
 
Building Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) ApplicationBuilding Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) Application
 
Course Introduction
Course IntroductionCourse Introduction
Course Introduction
 
Building Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) ApplicationBuilding Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) Application
 
Course Introduction
Course IntroductionCourse Introduction
Course Introduction
 

Recently uploaded

Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...lizamodels9
 
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts ServiceVip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Serviceankitnayak356677
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCRashishs7044
 
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130  Available With RoomVIP Kolkata Call Girl Howrah 👉 8250192130  Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Roomdivyansh0kumar0
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,noida100girls
 
Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Kirill Klimov
 
Cash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call GirlsCash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call GirlsApsara Of India
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation SlidesKeppelCorporation
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCRashishs7044
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechNewman George Leech
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesKeppelCorporation
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607dollysharma2066
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCRashishs7044
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncrdollysharma2066
 
Future Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionFuture Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionMintel Group
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdfKhaled Al Awadi
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCRashishs7044
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaoncallgirls2057
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCRashishs7044
 

Recently uploaded (20)

Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
 
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts ServiceVip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR
 
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130  Available With RoomVIP Kolkata Call Girl Howrah 👉 8250192130  Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
 
Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024
 
Cash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call GirlsCash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call Girls
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman Leech
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation Slides
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
 
Future Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionFuture Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted Version
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
 

0-Slot21-22-Strings.pdf

  • 1. Module G-Strings Slots 22 & 23: Theory and Demo. Slot 24: Exercise
  • 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
  • 13. Input Strings: scanf(…) How to accept blanks in a input string? ➔%[^n] conversion specifier. 13 Strings
  • 14. Input Strings: scanf(…) - Test Why? Why? Replace: scanf(“%s”, S) → scanf(“%10[^n]”, S) 14 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
  • 17. Input Strings: gets(…) 2293612 n1: 10 2293608 n2: 33 2293584 s 2293580 12 Overflow 17 Strings
  • 18. Input Strings: Do yourself a function for input s string 18 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()
  • 28. Some user-defined String Functions 28 Strings
  • 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)
  • 30. Counting number of words in a sentence
  • 31. Counting number of words in a sentence
  • 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:
  • 39. Array of Strings… Parameter in a function 39 Strings
  • 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
  • 41. Demo: Array of Names 41 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