String_PPT - Copy
String_PPT - Copy
9-3
• char name[11]; Initialization
• name[0]=‘a’;
• name[1]=‘n’;
0 1 2 3 4 5 6 7 8 9 10
• name[2]=‘m’;
a n m o l \0
• name[3]=‘o’;
• name[4]=‘l’;
If the actual string is longer than the width, the displayed field is
expanded with no padding.
9-6
An Example of Manipulating String with
scanf and printf
The dept is the initial memory address of the
string argument. Thus we don’t apply the &
operator on it.
9-8
9
Demo Program #1
Input/Output of Characters
and Strings
9-13
Comparison with 1D Integer Array
Aspect Integer Array String (Character Array) Similarities
Data Type int[] (array of integers) char[] (array of characters) Both are arrays.
Representation A sequence of integers A string is a sequence of Both store a
with no null terminator characters terminated by a sequence of
null character '\0' elements.
Accessing Elements arr[i] (Accessing str[i] (Accessing individual Both use indexing to
individual integers) characters) access elements
Length Size determined using Determined using strlen() Both have a defined
sizeof(arr) function (does not include null size.
character)
Manipulation Can use arithmetic Can use string manipulation Both can be
operations on integers functions (strcat(), strcmp(), traversed &
etc.) manipulated.
Terminator Not applicable (no null Required for proper string
terminator needed) manipulation (ends with '\0')
Input Handling Use scanf("%d", &arr[i]) Use scanf("%s", str) to read a Both can be read
to read an integer string with scanf.
Output Handling Use printf("%d", arr[i]) to Use printf("%s", str) to display Both can be
String Library Functions
9-18
Some String Functions from string.h
Function Purpose Example
strcpy Makes a copy of a string. strcpy(s1, “Hi”);
Q Q \0
strncmp functions.
String Comparison
(2/2)
Relationship Returned Value Example
str1 < str2 Negative “Hello”< “Hi”
str1 = str2 0 “Hi” = “Hi”
str1 > str2 Positive “Hi” > “Hello”
9-25
Task
1 ??
If the string "Alice in wonder land"
is fed to the following scanf( )
statement, what will be the
contents of arrays str1, str2, str3
and str4?