Uploaded by Raslen Gharssellaoui

C Programming Strings: Declaration, Input/Output, Functions

advertisement
Chapter 6
Strings
1
Chapter Outcomes
By the end of this chapter, the students will be able to:
• declare and initialize a string variable
• read and write a string variable.
• Use standard string library functions
2
Strings in C
• Strings are defined as an array of characters
terminated with a null character ‘\0’.
• When the compiler encounters a sequence of
characters enclosed in the double quotes (“), it
appends a null character \0 at the end by default.
Beginning
of string
"A String"
A
End of string
delimter
S t
r
i n g \0
• String literal values are represented by sequences of
characters between double quotes (“)
String vs character
String “”;
Empty string
String “H”;
char ‘H’;
H
H
\0
\0
• ‘H’ is a single character value (stored in 1 byte) as the ASCII
value for H
• “H” is an array with two characters, the first is H, the second
is the character value \0.
String – end of
string character
H
E
L
L
O
Array --- no
end of string
\0
H
E
L
L
O
The difference between a character array and a string is
the string is terminated with a special character ‘\0’.
4
Declaration of a string
• Declaring a string is as simple as declaring a one dimensional
array:
char str_name[size];
• str_name: is a name given to the string variable
• size: is used to define the length of the string, i.e the
number of characters the string can store.
• Example: char s[5];
5
Initialization of a string
• You can initialize strings in a number of ways.
• Examples:
By string
1. char S[] = "abcd";
literal
2. char S[50] = "abcd";
3. char S[] = {'a', 'b', 'c', 'd', '\0'}; By char
array
4. char S[5] = {'a', 'b', 'c', 'd', '\0'};
Index starts
from 0
S[0]
a
S[1]
b
S[2]
c
S[3]
d
S[4]
\0
In example (1) and (2), the C compiler automatically places the '\0' at
the end of the string,
6
Initialization of a string
Differences between char array and literal string:
✓ We need to add the '\0' at the end of the array explicitly whereas,
it is appended implicitly by the compiler in the case of the literal
string.
Example1:
7
String Input/Output
• Use %s field specification in scanf to read string
• Example 2:
Even though Ali Ben Amor was entered in the above program,
only “Ali" was stored in the name string. program will ignore Ben
Amor because, scanf() function stops reading when if finds a
white space.
8
String Input/Output
• C Can use the width value in the field specification to limit the
number of characters to be read.
• Example 3:
Enter name: Ahmed
Your name is Ahm.
Strings shorter than the field specification are read normally,
but if it is longer, like in this example, it will ignore the rest.
Using name without square brackets ‘[‘ and ‘]’ will give the base
address of this string. That’s why we have not used ‘&’ in this case as
we are already providing the base address of the string to scanf.
* However, you still can use ‘&’ before string name.
9
String Input/Output
• Use %s field specification in printf.
• Example 4:
• For %10s, it added 5 spaces before printing Ahmed, because the
length of entered string is 5 and the total length is 10 ,
• For %-10s, it is left aligned, because we use (-), and the extra spaces
(if any) will be added after the name.
10
Read and write a whole line gets and puts
• There are predefined functions gets() and puts() in C
language to read and display a line of string.
• Example 5:
gets() reads only one string at a time.
It stops when the newline character is read.
11
Traversing a String
• Difference between traversing an integer array and a string:
➢ To traverse an integer array, we need to know the length of the array,
➢ In the case of string, we may use the null character to identify the
end of the string and terminate the loop or using the predefined
function (strlen(s)).
Hence, there are two ways to traverse a string:
✓By using the length of string (strlen(str))
✓By using the null character (‘\0’).
12
Traversing String
Using the null character
Example 6:
Using the length of string
Example 7:
13
Exercise 1
Write a C program/ algorithm to find the
frequency of a character in a string.
Algorithm ex1
var
str:string
ch:character
i,frequecy: integer
begin
1- write(‘’enter a string’’)
2- read(str)
3- write(‘’enter a character to find
the frequency’’)
4- read(ch)
5- frequency0,
for(i=0, str[i]!=‘\0’,i++)
if(ch=str[i])
frequency  frequency +1
End for
6- write(‘’frequency of ‘’,ch, ‘’=‘’,
frequency)
end.
14
String functions
• Each string literal in a C program is stored at a different
location. So even if the string literals contain the same
string, they are not equal (in the == sense)
Example:
char string1[6] = “hello”;
char string2[6] = “hello”;
→ but string1 does not equal string2 (they are stored at
different locations)
string1=string2; → Compile error
• C provides a wide range of string functions for
performing different string tasks,
• Functions come from the utility library string.h
• #include <string.h> to use
15
String functions
• strlen(s1)
→ Returns the length of string s1.
Output:
16
String functions
• strlwr(s1) → converts all the uppercase characters in s1
to lowercase characters.
• strupr(s1) → converts all the lowercase characters in s1 to
uppercase characters.
Output:
17
String functions
• strcpy(s1,s2) → Copies string s2 into string s1.
Output:
18
String functions
• strcat(s1,s2) → Concatenates string s2 onto the end of
string s1.
Output:
19
String functions
• strcmp(s1,s2) → Returns
➢ 0, if s1 and s2 are the same;
➢ less than 0, if s1<s2;
➢ greater than 0, if s1>s2.
• Note : the strcmp function compares two strings lexicographically
based on their ASCII code.
20
Output:
String functions
• sprintf(s, string format, ...) → sends formatted
output to a string pointed to, by s.
21
Output:
String functions
• sscanf(s, c, ...) → reads formatted input from a string (s).
Output:
22
String functions
• atoi(s) → converts the string argument s to an integer.
• atof(s) → converts the string argument s to a float
number.
• #include <stdlib.h> to use
23
String functions
Output:
24
Exercise 2
• Write a C program to remove all characters in a string except alphabet
Output:
25
Download