Strings in C
Strings in C
Strings in C
1
C Strings
In C language a string is group of characters (or) array of characters, which is terminated by
C does not support string as a data type. It allows us to represent strings as character arrays. In
C, a string variable is any valid C variable name and is always declared as an array of characters.
3
Initializing location character by character
• Consider the following declaration With initialization:
char b[9]= { ‘C’, ‘O’,’M’,’P’,’U’,’T’,’E’,’R’};
C O M P U T E R \0
0 1 2 3 4 5 6 7 8
4
Partial array initialization
• Consider the following declaration With initialization:
char a[10]= {‘R’,’A’,’M’,’A’};
R A M A \ \ \ \ \0 \0
0 0 0 0
0 1 2 3 4 5 6 7 8 9
5
Initialization without specifying the size
• Consider the following declaration With initialization:
char a[]= {‘D’,’S’,’A’,’T’,’M’};
D S A T M
0 1 2 3 4
6
Array initialization with a string
• Consider the following declaration With string initialization:
char b[]=“COMPUTER”;
C O M P U T E R \0
0 1 2 3 4 5 6 7 8
7
Storing strings in memory:-
• In C a string is stored in an array of characters and terminated by \0
(null).
8
• Because strings are variable-length structure, we must provide
enough room for maximum- length string to store and one byte for
delimiter.
String Array
Why do we need null?
• A string is not a datatype but a data structure. String implementation
is logical not physical. The physical structure is array in which the
string is stored. The string is variable-length, so we need to identify
logical end of data in that physical structure.
9
String constant (or) Literal:-
10
STRING I/O FUNCTIONS
11
FORMATTED I / O FUNCTIONS
Here don't use “&‟ because name of string is a pointer to array. The problem with
scanf is that it terminates its input on the first white space it finds.
Ex:- NEW YORK
13
Writing strings on to the screen:-
Using formatted output functions:- printf with %s format specifier we
can print strings in different formats on to screen.
Ex:- char name[10];
printf(“%s”,name);
14
UNFORMATTED I / O
gets( ): (unformatted input function)
To read sequence of characters from keyboard with spaces in between and store them in memory
locations. gets( ) function is used.
Syntax:
gets(str);
str - string variable
Reads string of characters from keyboard till users presses “Enter key”.
17
strlen (str): string length
The function returns the length of the string str, it counts all the characters until ‘\0’ and returns the
total length.
Syntax:
int strlen (char str[ ]);
Example:
#include <stdio.h>
#include <string.h>
void main ( )
{
char s[ ] = “LAKSHMANA”;
printf (“length = %d”, strlen (s));
}
Output:
length = 9.
18
strcpy (dest,src) - String Copy
The function strcpy copies the contents of source string src to destination string dest
including ‘\0’. Here the size of destination string should be greater or equal to the source
string.
Syntax:
strcpy (char dest[ ], char src[ ]);
#include <stdio.h>
#include <string.h>
void main ( )
{
char src[ ] = “PROGRAM”;
char dest[10];
strcpy (dest, src);
printf (“Destination = %s”, dest);
19
}
strncpy (dest,src,n) - String Copy
The function strncpy copies ‘n’ number of characters of source string src to destination
string dest. Here the size of destination string should be greater or equal to the source
string.
Syntax:
strncpy (char dest[ ], char src[ ],int n);
#include <stdio.h>
#include <string.h>
void main ( )
{
char src[ ] = “PROGRAM”;
char dest[10];
strcpy (dest, src,4);
printf (“Destination = %s”, dest);
20
}
strcat (str1, str2) - append string str2 to str1.
This function is used to concatenate two strings. i.e., it appends one string at
the end of the specified string. Its syntax as follows:
strcat(string1,string2);
where string1 and string2 are one-dimensional character arrays.
This function joins two strings together. In other words, it adds the string2 to
string1 and the string1 contains the final concatenated string.
E.g., string1 contains prog and string2 contains ram, then string1 holds
program after execution of the strcat() function
Example:
char str1[10 ] = “VERY”;
char str2[ 5] =”GOOD”;
strcat(str1,str2); 21
A program to concatenate one string with another
using strcat() function
#include<stdio.h>
#include<string.h>
int main()
{
char s1[30],s2[15];
printf(“\n Enter first string:”);
gets(s1);
printf(“\n Enter second string:”);
gets(s2);
if(sizeof(s1)>=strlen(s1)+srtlen(s2))
{
strcat(string1,string2);
printf(“\n Concatenated string=%s”,string1);
}
else
printf(“Concatenation not possible\n) 22
}
strcmp() compare two strings str1 & str2.
The strcmp() function compares two strings and returns 0 if both strings are identical
Present in string.h library
Syntax:
int strcmp (const char* str1, const char* str2);
23
Return Value from strcmp()
ASCII
A=65 a=97
B=66 b=98
Return Value Remarks
C=67 c=99
if both strings are identical .
0 .
(equal)
.
if the ASCII value of the first .
negative unmatched character is less
than second.
24
ASCII
Example: C strcmp() function A=65 a=97
B=66 b=98
C=67 c=99
#include <stdio.h>
str1 str2 str3
#include <string.h>
a a a
int main() str1[0] str2[0] str3[0]
{ char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd"; b b
str1[1] str2[1] b str3[1]
int result1,result2;
c c
str1[2] str2[2] C str3[2]
// comparing strings str1 and str2
result1 = strcmp(str1, str2); d d d
str1[3] str2[3] str3[3]
printf("strcmp(str1, str2) = %d\n", result1);
\0 \0 \0
str1[4] str2[4] str3[4]
// comparing strings str1 and str3
result2 = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result2); result1=str1[2]-srt2[2] result2=str1[4]-srt3[4]
=99-67 =\0 - \0
}
=32 =0-0
=0
25
• Output
ASCII
strcmp(str1, str2) = 32 A=65 a=97
B=66 b=98
strcmp(str1, str3) = 0 C=67 c=99
26
Array of strings
27
Array of strings
We have array of integers, array of floating point numbers, etc.. similarly we
have array of strings also.
Collection of strings is represented using array of strings.
Declaration:-
char arr[row][col];
where,
arr - name of the array
row - represents number of strings
col - represents size of each string
28
Initialization:-
char arr[row][col] = {list of strings };
Example:-
0 1 2 3 4 5 6 7 8 9
char city[5][10] = { “DELHI”,
0 D E L H I \0
“CHENNAI”,
“BANGALORE”, 1 C H E N N A I \0
“HYDERABAD”,
2 B A N G A L O R E \0
“MUMBAI” };
3 H Y D E R A B A D \0
4 M U M B A I \0
In the above storage representation memory is wasted due to the fixed length
for all strings.
29
Write a C program to print array of strings:
include <stdio.h>
int main()
{
int i;
char city[5][10] = { "DELHI",
"CHENNAI",
"BANGALORE",
"HYDERABAD",
"MUMBAI" };
printf("strings are:\n");
for(i=0;i<=5;i++)
{
printf("%s\n", city[i]);
}
}
30
Write a C program to read and print array of strings.
#include <stdio.h>
int main()
{ 0 1 2 3 4 5 6 7 8 9. . .
int i,n;
char city[10][20]; 0
printf("Enter the number of string:\n");
scanf("%d", &n); 1
31
OUTPUT:
Enter the number of string:
5
enter the strings:
DSATM
DSCE
DSI
DSBA
DSU
strings are:
DSATM
DSCE
DSI
DSBA
DSU
32
Write functions to implement string operations such as compare, concatenate, string length.
}
int string_length(char s1[]) int compare_strings(char s1[], char s2[])
void concatenate(char s1[], char s2[])
{ {
{
int i = 0; int i, j;
int i = 0;
while (s1[i] == s2[i]) i = 0;
while (s1[i] != '\0') { while (s1[i] != '\0')
i++; if (s1[i] == '\0' || s2[i] == '\0') {
break;
return i; i++;
i++;
} }
}
if (s1[i] == '\0' && s2[i] == '\0') j = 0;
return 0; while (s2[j] != '\0')
else {
return 1; s1[i] = s2[j];
} j++;
i++;
}
s1[i] = '\0';
}
OUTPUT:
Input string1
dsatm
Input string2
dsi
Length of string1: 5
Length of string2: 3
Unequal string
String obtained on concatenation: dstamdsi
Write a C program that reads a sentence and
prints the frequency of each of the vowels
and total count of consonants
36
#include <stdio.h>
void main()
{ 0 1 2 3 4 5 6 7 8 9
char str[80]; 10 11 12 13 14 15 16
int i, vowels = 0, consonants = 0;
W E L C O M E T O D S A T M \0
printf("Enter a str \n");
gets(str);
38
To print frequency of each vowel and total
count of consonants in a sentence
39
#include<stdio.h>
void main()
{
char s[100];
printf("\nIn the sentence \"%s\" :",s);
int j, ac=0, ec=0, ic=0, oc=0, uc=0, cc=0;
printf("Enter a sentence\n");
gets(s); printf("\nThe frequency vowel of A/a is %d",ac);
for(j=0;s[j]!='\0';j++)
{ printf("\nThe frequency vowel of E/e is %d",ec);
if(isalpha(s[j]))
{ printf("\nThe frequency vowel of I/i is %d",ic);
if(s[j]=='A'||s[j]=='a')
ac++;
printf("\nThe frequency vowel of O/o is %d",oc);
else if(s[j]=='E'||s[j]=='e’)
ec++; printf("\nThe frequency vowel of U/u is %d",uc);
else if(s[j]=='I'||s[j]=='i’)
ic++; printf("\nThe total count of all consonents is %d",cc);
else if(s[j]=='O'||s[j]=='o’)
oc++; }
else if(s[j]=='U'||s[j]=='u’)
uc++;
else if(s[j]!=' ‘)
cc++;
}
}
40