0% found this document useful (0 votes)
5 views

String_PPT - Copy

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

String_PPT - Copy

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

3.

Problem Solving using


Array Techniques

3.2 Strings and


Operations on Strings.
Strings
• C implements the string data structure using arrays
of type char.
• Since string is an array, the declaration of a string
is the same as declaring a char array.
• General form: char stringname[size];
• Examples:
– char string_var[30];
– char string_var[20] = “Initial value”;
– char name[10];
Memory Storage for a
String
• Default initialized with Garbage Value.
• The string is always ended with a null character ‘\0’.
• The characters after the null character are ignored.
• e.g., char str[20] = “Initial value”;
[0] [13]
I n i t i a l v a l u e \0 ? ? …

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

• char name[11]= {‘a’, ‘n’, ‘m’, ‘o’, ‘l’};


• char name[11]= “anmol”;
• char name[ ] = “anmol”;
• char name[ ] = {‘a’, ‘n’, ‘m’, ‘o’, ‘l’}; 9-4
Input/Output of a
String
• The placeholder %s is used to represent string
arguments in printf and scanf.
– printf(“Topic: %s\n”, string_var);
• The string can be right-justified by placing a
positive number in the placeholder.
– printf(“%8s”, str);
• The string can be left-justified by placing a
negative number in the placeholder.
– Printf(“%-8s”, str); 9-5
Right and Left Justification
of Strings

The “%8s” placeholder displays a string which is right-


justified and in 8-columns width.

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.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.


Execution of scanf
("%s", dept);
• Whenever encountering a white space, the scanning stops
and scanf places the null character at the end of the
string.
• e.g., if the user types “MATH 1234 TR 1800,” the
string “MATH” along with ‘0’ is stored into dept.

9-8

9
Demo Program #1
Input/Output of Characters
and Strings

• The stdio library provides getchar function which gets


the next character from the standard input.
–“int ch = getchar();” is the same as
“scanf(“%c”, &ch);”
–Similar functions are putchar.

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

• The string can not be copied by the


assignment operator ‘=’.
– e..g, “str = “Test String”” is not valid.
• C provides string manipulating functions in
the “string.h” library.

9-18
Some String Functions from string.h
Function Purpose Example
strcpy Makes a copy of a string. strcpy(s1, “Hi”);

strcat Appends a string to the end of strcat(s1, “more”);


another string
strcmp Compare two strings strcmp(s1, “Hu”);
alphabetically
strlen Returns the number of characters strlen(“Hi”)
in a string returns 2.
strrev Reverses the string passed to it strrev(“Hi");
as an argument. 9-19
Demo Program #2
Functions strcpy and strncpy
• Function strcpy copies the string in the
second argument into the first argument.
– e.g., strcpy(dest, “test string”);
– The null character is appended at the end
automatically.
– If source string is longer than the destination string, the
overflow characters may occupy the memory space used
by other variables.
• Function strncpy copies the string by specifying
the number of characters to copy.
– You have to place the null character manually.
– e.g., strncpy(dest, “test string”, 6); dest[6] = ‘\0’;
– If source string is longer than the destination string, 9-21

the overflow characters are discarded automatically.


Functions strcat and strlen
• Functions strcat and strncat
concatenate the first string argument with the
second string argument.
– strcat(dest, “more..”);
– strncat(dest, “more..”, 3);
• Function strlen is often used to check the
length of a string (i.e., the number of
characters before the fist null character).
– e.g., dest[6] = “Hello”;
strncat(dest, “more”, 5-strlen(dest));
dest[5] = ‘\0’; 9-22
Distinction Between Characters and
Strings
• The representation of a char (e.g., ‘Q’) and
a string (e.g., “Q”) is essentially different.
– A string is an array of characters ended with the null
character.

Q Q \0

Character ‘Q’ String “Q”


9-23
String Comparison
(1/2)
• Suppose there are two strings, str1 and str2.
– The condition str1 < str2 compare the initial
memory address of str1 and of str2.
• The comparison between two strings is done by
comparing each corresponding character in them.
– The characters are comapared against the ASCII
table.
– “thrill” < “throw” since ‘i’ < ‘o’;
– “joy” < joyous“;
• The standard string comparison uses the
strcmp and 9-24

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”

• e.g., we can check if two strings are the same by


if(strcmp(str1, str2) != 0)
printf(“The two strings are different!”);

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?

char str1[ 20 ], str2[ 20 ], str3[ 20 ], str4[ 20 ] ;


scanf( "%s%s%s%s", str1, str2, str3, str4 ) ;
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?

char str1[ 20 ], str2[ 20 ], str3[ 20 ], str4[ 20 ] ;


str1 – Alice
scanf( "%s%s%s%s", str1, str2, str3, str4 ) ;
str2 – in
str3 – wonder
str4 – land
Quick recap

Fill in the blanks:


(a) "A" is a string whereas ‘A’ is a character.
(b) A string is terminated by a null character, which is
written as \0.
(c) The array char name[10] can consist of a maximum
of 9 characters.
(d) The array elements are always stored in consecutive
memory locations.
Write a program that generates and prints the
G
R
Fibonacci words of order 0 through 5. For example,
A f(0) = "A", f(1) = "B", f(2) = "BA", f(3) = "BAB",
D
E
f(4) = "BABBA", etc.
D Using string.h library functions
P
R
O
G
R
A
M
Character Analysis and Conversion
• The <ctype.h> library defines facilities for character
analysis and conversion.
Functions Description
isalpha Check if the argument is a letter

isdigit Check if the argument is one of the ten digits

isspace Check if argument is a space, newline or tab.

tolower Converts the lowercase letters in the


argument to upper case letters. 9-31
https://cse.poriyaan.in/topic/miscellaneous-string-a
nd-character-functions-50356/#google_vignette
Demo Program #3 &4
Conversions Between Strings
Numbers
• The <stdlib.h> defines some basic functions
for conversion from strings to numbers:
– atoi(“123”) converts a string to an integer.
– atol(“123”) converts a string to a long integer.
– atof(“12.3”) converts a string to a float.
• However, there is no functions such as itoa,
itof,
…etc,
– because there is a function called sprintf which can 9-34

converts many formats to a string.


The sprintf and sscanf Functions
• The sprintf function substitutes values for
placeholders just as printf does except that
it stores the result into a character array
– sprintf(s, “%d%d%d”, mon, day,
year);
• The sscanf function works exactly like
scanf except that it takes data from the
string as its input argument.
– sscanf(“ 11 22.2 Hello”, “%d%lf%s”,
&num, &val, word); 9-35
Arrays of
Strings
• An array of strings is a two-dimensional
array of characters in which each row is one
string.
–char names[People][Length];
–char month[5][10] = {“January”,
• “February”, “March”, “April”,
“May”};
9-36

You might also like