Strings
Strings
Introduction to string
• String is a sequence of characters enclosed in double quotes.
• Normally, it is used for storing data like name, address, city etc.
• ASCII code is internally used to represent string in memory.
• In‘C’, each string is terminated by a special character called null character
represented as ‘\0’ or NULL.
• Because of this reason, the character array must be declared one size longer
than the string required to be stored.
• char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
• char greeting[] = "Hello";
2
Reading strings
• The format specifier %s is used to read a string in the character
array.
• For example,
• char name[20];
• scanf(“%s”,name); OR gets(name);
• Unlike previous scanf calls, in the case of character arrays, the
ampersand (&) is not required before the variable name.
• The advantage of gets( ) is that we can read string involving blanks,
tabs. While the scanf( ) reads only upto blank or tab character. So,
scanf( ) is used to read word while gets( ) can be used read sentence
involving many words.
3
printing strings
• The format specifier %s is used to print a string in the character
array.
• For example,
• char name[ ] = “Hello”;
• printf(“%s”,name); OR puts(name);
• puts() can print only one string at a time, while one printf( ) can
print multiple strings by using %s many times in the printf( ).
• char name[ ] = “ABC”;
• char surname[ ] = “XYZ”;
• printf(“%s %s”, name, surname); OR
• puts(name);
• puts(surname);
4
5
Arithmetic operations on
characters
• To write a character in its integer representation, we may write it as an
integer. For example, if the machine uses the ASCII representation,
then,
• x = ‘a’;
• printf(“%d \n”, x);
• will display the number 97 on the screen.
• It
is possible to perform arithmetic operations on the character
constants and variables. For example,
• x = ‘z’ – 1
• This is a valid statement. In ASCII, the value of ‘z’ is 122, and therefore, the statement
will assign the value 121 to the variable x.
6
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 Character ‘Q’
• Q \0 String “Q”
7
String manipulation functions
Sr. String Syntax Explanation
No function
9
strlen( )
10
Finding length of string without
using strlen( )
11
strlen vs sizeof
• strlen returns you the length of the string stored in array, however
sizeof returns the total allocated size assigned to the array.
Consider the given example, then the following statements would
return the below values.
• strlen(str1) returned value 11.
• sizeof(str1) would return value 20 as the array size is 20 (see the
first statement in main function).
12
strcpy( )
• Functionstrcpy() copies the content of one string to the content of
another string. It is defined under "string.h" header file.
• It takes two arguments.
• Syntax of strcpy()
• Here,source and destination are both the name of the string. This
statement, copies the content of string source to the content of string
destination.
13
strcpy( )
14
Copy one string to another without
using strcpy( )
15
strncpy( )
• Functionstrncpy() copies the content of one string to the content of
another string by specifying the number of characters to copy. It is
defined under "string.h" header file.
• It takes two arguments.
• Syntax of strncpy() strncpy(dest, src, n);
• Afterusing this function, you need to manually put null character at
the end of destination string dest[n] = ‘\0’;
• Here,source and destination are both the name of the string. This
statement, copies the content of string source to the content of string
destination.
16
strncpy( )
17
Copy a string without using
strncpy( )
18
strcat( )
• In C programming, strcat() concatenates(joins) two strings.
• It takes two arguments, i.e, two strings and resultant string is stored in
the first string specified in the argument.
• Function strcat() is defined under "string.h" header file.
• Syntax of strcat()
• strcat(first_string,second_string);
19
Concatenate two strings without
using strcat( )
20
strncat( )
• It concatenates n characters of str2 to string str1. A terminator char
(‘\0’) will always be appended at the end of the concatenated string.
21
strcmp( )
•C does not permit the comparison of two strings directly. That is, the
statements such as
• if (name1 == name2)
• if (name1 == “ABC”) are not permitted. It is therefore necessary to compare
the two strings to be tested, character by character. The comparison is done
until there is a mismatch or one of the strings terminates into a null
character, whichever occurs first.
• InC, strcmp() compares two string and returns value 0, if the two
strings are equal. It is defined under "string.h" header file.
• Function strcmp() takes two arguments, i.e, name of two string to
compare.
• Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0
if s1>s2.
• Syntax of strcmp()
• temp_variable = strcmp(str1, str2);
22
strcmp( )
23
strcmp( )
• Iftwo strings are not equal, strcmp() returns positive value i.e. 1 if
ASCII value of first mismatching element of first string is greater
than that of second string and negative value i.e. -1 if ASCII value of
first mismatching element of first string is less than that of second
string. For example:
• Since, ASCII value of 'a' is less than that of 'c', variable temp will be
negative.
24
Compare two strings without using
strcmp( )
25
strcmpi( )
• strcmpi( ) function in C is same as strcmp() function. But, strcmpi( )
function is not case sensitive. i.e, “A” and “a” are treated as same
characters. Where as, strcmp() function treats “A” and “a” as
different characters.
26
Some String programs
• Write a program to find the frequency of a character entered by user in a
string.
• Write a program to compare case insensitive strings.
• Write a program to swap character at odd positioned index with the one
at even positioned index.
• Write a program to find the total number of vowels, consonants, digits
and spaces appearing in a string.
• Write a program to remove all other characters in a string except the
alphabets.
• Write a program to calculate frequency of each character in a given
string.
• Write a program to sort strings in dictionary order.
27
getchar( ) and putchar( )
• The int getchar(void) function reads the next available character
from the screen and returns it as an integer. This function reads
only single character at a time.
• The int putchar(int c) function puts the passed character on the
screen and returns the same character. This function puts only
single character at a time.
28
Difference between getchar() and
getch()
• If you use getchar(), you need to press enter key after
entering the
character in the console window. But, if you use getch(), you don’t
need to press enter key after entering the character in the console
window (Because it does not use any buffer, so the entered
character is immediately returned without waiting for the enter
key).
• If
you use getchar(), you can see the character that is being
entered in the console window. But, if you use getch(), you can’t
see the character that is being entered in the console window.
29
Character Analysis and Conversion
• The <ctype.h> library defines facilities for character analysis and
conversion.
Functions Description
int isalnum(int c) This function checks whether the passed character is alphanumeric.
int isalpha(int c) This function checks whether the passed character is alphabetic.
int isdigit(int c) This function checks whether the passed character is decimal digit.
int islower(int c) This function checks whether the passed character is lowercase letter.
int isupper(int c) This function checks whether the passed character is an uppercase letter.
30
getc() and putc() function
• getc(), putc() functions are file handling function in C programming
language which is used to read a character from a file (getc) and
display on standard output or write into a file (putc).
• getc()reads a single character from a given input stream and
returns the corresponding integer value (typically ASCII value of
read character) on success. It returns EOF on failure.
• int getc(FILE *stream);
• The difference between getc() and getchar() is getc() can read from
any input stream, but getchar() reads from standard input. So
getchar() is equivalent to getc(stdin).
• The putc() function converts c to unsigned char and then writes c to
the output stream at the current position. The putchar() is
equivalent to putc(c, stdout).
• int putc(int c, FILE *stream);
31
32