String
String
1
Strings
• In C programming, a string is a sequence of
characters terminated by the end-of-string
sentinel ‘\0’ (null character). For example
2
How to declare a string
3
How to initialize strings
4
Read String from the user
You can use the scanf ( ) function to read a string. The scanf ( ) function reads the
sequence of characters until it encounters whitespace (space, newline, tab, etc.).
Output
5
Read String from the user (Cont.)
Even though Tanwi Nkiamboh was entered in the above program, only Tanwi was
stored in the name string. Thios is because there was a space after Tanwi.
Also notice that we have used the code name instead of &name with scanf ( )
This is because name is a char array, and we know that array names decay to
pointers in C.
Thus, the name in scanf ( ) already points to the address of the first element in the
string, which is why we dont need to use &.
6
How to read a line of text
• You can use the fgets( ) function to read a line of string.
• And, you can use puts( ) to display the string
Example 2: fgets( ) and puts( )
• Output
7
Access Characters of a String
Output:
8
Changing Characters of a String
Output:
9
Programming Task 1
Create a program that takes your full name as
input and prints your name. Then, change the
first letter of your name to X.
if your name is Agbor James, it will become
Xgbor James
10
String functions
You need to often manipulate strings according to
the need of a problem. Most, if not all, of the time
string manipulation can be done manually but, this
makes programming complex and large.
To solve this, C supports a large number of
strings handling functions in the standard library «
string.h ».
Few commonly used string handling functions are
discussed below:
11
String functions (Cont.)
Strcpy(s1, s2): Copies string s2 into string s1.
Strcat(s1, s2): Concatenates string s2 onto the end of strings1.
Strlen(s1): Returns the length of string s1.
Strcmp(s1, s2) : Returns 0 if s1 and s2 are the same; less than
0 if s1<s2; greater than0 if s1>s2.
Strlwr(): converts string to lowercase
Strupr(): converts string to uppercase
Note: You have to include the code below to run string handling
functions.
gets( ): To take string input from the user
puts( ): To display
12
String Function Example
13
Programming Task 2
Write a c program to compare two strings and
print the larger string and its length.
Write a c program to find the length of a string
without using the strlen( ) function.
Concatenate two strings without using strcat( )
Write a c program to count the number of
vowels, consonants, digits and white spaces in a
string entered by a user.
14