Character Array and String

2,503 views 27 slides Sep 19, 2020
Slide 1
Slide 1 of 27
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27

About This Presentation

This is a short presentation on character array and strings in c programming. It includes basic and important facts about the topics.


Slide Content

Presentation on
Character Array & Strings
•Prepared by-
Tasnima Hamid
Program-Internet of Things (IoT)
Department-Information and Communication Technology (ICT)
Bangabandhu Sheikh Mujibur Rahman Digital University, Bangladesh.

Overview
▪Character Array &
Strings
▪Declaration of a string.
▪Initialization of a string.
▪Reading strings.
▪Writing strings.
▪String Functions
▪Arithmetic Operations

Character Arrays and Strings and Their Uses
•Astringisrepresentedusingacharacterarrayandisalways
terminatedwiththenullcharacter‘\0’
•Astringisasequenceofcharactersthatistreatedasasingle
dataitem.
•Stringsareactuallyone-dimensionalarray.
•Characterstringsareoftenusedtobuildmeaningfulandreadable
programs.

Memory Representation of String
Index
01234567891011
value
TEAM AMPHAN\0
Address
100110021003100410051006100710081009101010111012
•12 bytes of memory is allocated to store 12 characters.

Declaring
•Callowstorepresentstringsascharacterarraysratherthan
strings.
•AstringvariableisanyvalidCvariablenameandisalways
declaredasanarrayofcharacters.
•Thegeneralformofdeclarationofastringvariableis
charstring_name[size];
•Here,string_nameisanynamegiventostringvariableandsize
isusedtodefinethelengthofthestringorthenumberof
charactersinthestring.
•Thesizeshouldbeequaltothemaximumnumbersofcharacters
inthestringplusone.

Initializing A String
•A string can be initialized in several ways
char str[ ] = “Team Amphan”;
char str[12] = “Team Amphan” ;
char str[ ] = {‘T’, ‘e’, ‘a’, ‘m’, ‘ ’, ‘A’, ‘m’, ‘p’, ‘h’, ‘a’, ‘n’, ‘\0’ } ;
char str[12] = {‘T’, ‘e’, ‘a’, ‘m’, ‘ ’, ‘A’, ‘m’, ‘p’, ‘h’, ‘a’, ‘n’, ‘\0’ } ;

Reading String from Terminal
•Strings can be read in several ways using-
scanf() getchar() gets() Line of Text
•Syntax-
char string_name [string_size];
scanf(“%ws”, string_name);
•%s and %ws can read only strings without whitespaces.
•Using getchar
char ch;
ch=getchar();//no parameter
•Using gets
gets(str); //one parameter
•%[. .] can be used to read a line containing a variety of characters, including whitespaces.
•Using Line of Text
char a [80];
scanf(“%[^\n]”, a);

Writing Strings to Screen
•Strings can be written in several ways using-
printf() putchar() puts()
•Using printf function
printf(“%s”, string_name);
•C uses putchar to output the values of character variables.
char ch =‘A’;
putchar (ch); \\equivalent to printf(“%c”, ch);
•Another convenient way of printing string values is to use the function
puts. puts(str);

Char str[12]=“Team Amphan”
9

String Handling Functions
The header file <string.h> contains many string manipulation
functions. Such as-
Function Name Function Action/Purpose
String Length strlen Get string length.
String Copy strcpy Copy a string.
String Concatenation strcat Concatenate two strings.
String Compare strcmp Compare two strings.
String Reverse strrev Return the string reversed.
Lower to Upper strupr Convert to upper case.
Upper to Lower strlwr Convert to lower case.
Character Existence strchr Searching a character.

String Length
•This function counts and returns the number of characters in a
string. The counting ends at the first null character.
int n = strlen(string);

String Copy
•Syntax-
strcpy(string1,string2);
Here,string1isthedestinationstringandstring2isthesource
string.
strncpy(string1,string2,n);
Thisfunctioncopiesonlytheleft-mostncharactersofthe
sourcestringtothedestinationstring.

Copying A String

Comparison of Two Strings
•Syntax-
strcmp(string1,string2);
Here,string1isthedestinationstringandstring2isthesourcestring.
strncmp(string1,string2,n);
Thisfunctioncomparestheleft-mostncharactersofthesourcestring
andthedestinationstringandreturns.
Itreturnsintegervaluewhichincludes(0,positiveandnegative).
•DecimalequivalentofASCIIcodeofais97
•DecimalequivalentofASCIIcodeofAis65
•DecimalequivalentofASCIIcodeof0is48

When return value is negative When return value is positive

Comparing Strings
•Syntax-
•strncmp(string1, string2, n);

String Concatenation
•Syntax-
strcat(string1,string2);
Here,string1isthedestinationstringandstring2isthesource
string.
•Itaddssecondstringattheendofthefirststring.
strncat(string1,string2,n);
Thisfunctionconcatenatesonlytheleft-mostncharactersof
thesourcestringattheendofdestinationstring.

String Concatenation

Converting Cases
•Syntax
strupr(string_name);
Thisfunctionconvertsthelowercaselettersofthestringintouppercaseletters.
•Syntax
strlwr(string_name);
Thisfunctionconvertstheuppercaselettersofthestringintolowercaseletters.

String Reverse
•Syntax
strrev(string_name);
This function reverses the character string.

Character Existence in String
•Itsearchesstringstring1forcharacterch.
•strchr(string1,‘ch’);
Thisfunctionwilllocatethefirstoccurrenceofthecharacter
‘ch’andthecall.
•strrchr(string1,‘ch’);
Thisfunctionwilllocatethelastoccurrenceofthecharacter
‘ch’andthecall.

Character Existence in String

String Subset
•Syntax
strstr(string1,string2);
•Thisfunctioncanbeusedtolocateasub-stringinastring.
•Thisfunctionsearchesthestringstring1toseewhetherthe
stringstring2iscontainedinstring1.Ifyes,thefunction
returnsthepositionofthefirstoccurrenceofthesub-string.
Otherwise,itreturnsanullpointer.

Arithmetic Operations on Characters
•Way 1: Displays ASCII value[ Note that %d in Printf ]
char x = 'a’;
printf("%d",x); // Display Result = 97
•Way 2 : Displays Character value[ Note that %c in Printf ]
char x = ‘a’;
printf("%c",x); // Display Result = a
•Way 3 : Displays Next ASCII value[ Note that %d in Printf ]
char x = 'a' + 1 ;
printf("%d",x);// Display Result = 98 ( ascii of 'b' )

Arithmetic Operations on Characters
•Way 4 Displays Next Character value[Note that %c in Printf ]
char x = 'a' + 1;
printf("%c",x);// Display Result = 'b'
•Way 5 : Displays Difference between 2 ASCII in Integer[Note %d in Printf ]
char x = 'z' -'a’;
printf("%d", x);/* Display Result = 25 (difference between ASCII of z and a ) */
•Way 6 : Displays Difference between 2 ASCII in Char [Note that %c in Printf ]
char x = 'z' -'a';
printf("%c", x); /* Display Result = ↓ ( difference between ASCII of z and a ) */
•The C library supports a function that converts a string of digits into their integer
values.
x=atoi(string);

Arithmetic Operations on Characters

Thank You