Vignan CP UNIT-4 Strings
Vignan CP UNIT-4 Strings
Vignan CP UNIT-4 Strings
UNIT-4
STRINGS
INTRODUCTION: - In ‘C' language the group of characters, digits, and symbols enclosed
within quotation marks are called as string. The string is always declared as character arrays.
Every string is terminated with’\0’ (NULL) character the NULL character is a byte with all bits
at logic zero.
EX:-
1. Each character of the string occupies 1 byte of memory the last character is always’\0’.
2. It is not compulsory to write ‘\0’ in string. The compiler automatically puts ‘\0’ at the end
of the character array or string.
3. The characters of string are stored in contiguous (neighboring) memory locations.
S T U D E N T \0
General form:-
garbage value
Ex:- :- #include<stdio.h>
void main ()
{
char name [7] = {‘S’,’T’,’U’,’D’,’E’,’N’,’T’};
char name1 [3] = {‘h’,’i’};
printf(“name=%s”,name);
printf(“name1 = %s”,name1);
}
Output: studenthi
hi
Ex: #include<stdio.h>
main()
{
printf("\nMemory Requirement of XYZ is %dbytes\n",sizeof("XYZ"));
}
Output: Memory Requirement of XYZ is 4bytes
Ex: #include<stdio.h>
main()
{
char s[10]=”xyz”;
printf("\nThe first character of the string literal XYZ is %c\n", *s);
printf("\nThe second character of the string literal XYZ is %c\n", *(s+1));
}
The familiar input function scanf can be used with %s format specification to read in a string of
characters.
Ex:-
char name[10];
scanf(“%s”,name);
The problem with the scanf function is that it terminates its input on the first white space it
finds.
Computer programming
Then only the string ‘computer’ will be read into the array address, since the blank space after
the word ‘computer’ will terminate the reading of string.
The scanf function automatically terminates the string that is read with a null character.
The ampersand (&) is not required before the variable name.
If we want to read the entire line computer programming use two character arrays.
The format specifier "%[^\n]" tells to the compiler that read the characters until "\n" is not found.
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
scanf("%[^\n]",name);
printf("Name is: %s\n",name);
return 0;
}
1. The width w >= The number of characters typed in. The entire string will be stored in the
string variable.
2. w < the number of characters in the string. The excess characters will be truncated& left
unread.
char name [10];
scanf(“%5s”, name);
KRISHNA
K R I S H \0 ? ? ? ?
0 1 2 3 4 5 6 7 8 9
The printf function with %s format to print strings to the screen. The format %s can be used
to display on array of characters that is terminated by the null character.
Ex:- printf(“%s”,name);
we can also specify the precision with which the array is displayed.
various formats are shown to print the string with width specified.
1. printf(“%s”,text); prabhakar
2. printf(“%.5s”,text); prabh
3. printf(“%.8s”,text); prabhaka
4. printf(“%.15s”,text); prabhakar
5. printf(“%-10.4s”,text); prab
6. printf(“%11s”,text); prabhakar
5
The getchar() function is a part of standared ‘C’ language i/o library .It returns a single
character from a standared input device. The function does not require any arguments through a
pair of empty parentheses.
syntax:
character_variable=getchar();
Ex:-
char c;
c=getchar();
printf(“%c”,c);
Reading a string of text containing whitespaces is to use the library function gets available in
the <stdio.h> header file.
syntax:- gets(string_variable);
Ex:-
char line[80];
gets(line);
printf(“%s”,line);
It transmits a single character to a standard output device. The character being transmitted
will normally be expressed as an argument to the function enclosed in parentheses following the
word putchar.
syntax:- putchar(character_variable);
Ex:-
char c;
c=getchar();
putchar(c);
Character Arrays:
Ex:- char name[ ]={‘A’, ‘K’, ‘S’, ‘H’, ‘A’, ’y’, ‘\0’};
Terminating the string with null ‘\0’ is important, because it is the only way the
functions that work with a string can know where the string ends.
A K S H A Y \0
Each character in the array occupies a memory of one byte (including ‘\0’)
In these declarations ‘\0’ is not necessary C inserts ‘\0’ automatically at the end of the string.
7
#include<stdio.h>
void main()
char name[20];
scanf(“%s”,name);
Character strings are often used to build meaningful and readable programs. The common
operations performed on character strings include:
Every C compiler provides a large set of string handling function which are contained in header
file <string.h>
The C library supports a large number of string-handling functions that can be used to carry out
many of the string manipulations.
8
Functions
Description
strlen()
Determines length of a string
strcpy()
Copies a string from source to destination
strcat()
Appends source string to destination string
1.strlen function:
Syntax: n= strlen(string);
Where n is a an integer variable, which receives the value of the length of the string. The
argument may be a string constant. The counting ends at the first null character.
2.strlen(“7893”)= 4
3.strlen(“+-$”) = 3
4.strlen(“A2$”) = 3
6.char a[ ]=”swathi”;
Strlen(a)=6
7. strlen(7892) // error
#include<stdio.h>
#include<string.h>
void main()
9
char text[20];
int len;
gets(text);
len=strlen(text);
2.strcpy function:
Syntax: strcpy(string1,string2);
1. strcpy(city,”delhi”);
2. char a[20];
Strcpy(a,”rama rao”);
Rama rao is copied to array ‘a’. Array ‘a’ contains rama rao.
a=”rama rao” is invalid. We can’t use array name on left hand side of “=” as it modifies base
address of the array which is not possible.
3. char a[ ]=”7892”;
char b[10];
10
strcpy(b,a);
We can use array name on left hand side of = , only in declaration statement but not in
executable statement.
strcpy(a,strcpy(b,”hyd”));
/* C program to copy the contents of one string to another string by using strcpy()
*/
#include<stdio.h>
#include<string.h>
void main()
printf(“enter ur name”);
gets(ori);
strcpy(dup,ori);
3.strcmp function:
11
This function compares two strings for finding whether they are same or different. This function
discriminates between small and capital letters.
char str2[20]=”hello”;
Characters of these strings are compared one by one. In case of a mismatch the function returns
non-zero value otherwise zero i.e. when the two strings are same strcmp() returns the value zero.
If they are different it returns the numeric difference b/w the ASCII values of non-matching
characters.
Syntax: strcmp(string1,string2);
Ex: strcmp(“their”,”there”);
Will return a value of -9 which is the numeric difference between ASCII “i”(105) and ASCII
“r”(114) i.e. “i” minus “r” in ASCII code (105-114 ) is -9.
#include<stdio.h>
#include<string.h>
void main()
int diff;
gets(str1);
gets(str2);
diff=strcmp(str1,str2);
12
if(diff==0)
else
4.Strcat Function:
Syntax: strcat(source,target);
strcat(text1, text2);
/* C program to append second string at the end of the first string using strcat() */
#include<stdio.h>
#include<string.h>
void main()
gets(text1);
gets(text2);
strcat(text1, “ “);
strcat(text1, text2);
13
5 . Strrev Function:-
This function simply reverses the given string. This function takes only one argument and
returns one argument.
Syntax: strrev(string);
strrev(x);
2) char x[]=”4000”;
strrev(x);
#include<stdio.h>
#include<string.h>
void main()
char text[20];
gets(text);
puts(strrev(text));
}
14
Functions
Description
strncpy()
Copies characters of a string to another string up to the
specified length
stricmp()
Compares two strings(function does not discriminate b/w
small & capital letters)
strnicmp()
Compares characters of two strings up to the specified
length. Ignores case.
strlwr()
Converts upper case characters of a string to lower case
strupr()
Converts lower case characters of a string to upper case
strdup()
Duplicates a string
strchr()
Determines first occurrence of a given character in a string
strrchr()
Determines last occurrence of a given character in a string
strncat()
Appends source string to destination string up to a specified
length
1 .strncpy function:
This function copies specified length of characters from source to destination string.
Syntax: strncpy(destination,source,n);
Where n is the number of left most characters of the source string to be copied.
char s2[20];
strncpy(s2,s1,5);
15
This statement copies the first 5 characters of the source string s1 into the target string
s2.Therefore s2 contains “Londo”.
#include<stdio.h>
#include<string.h>
void main()
int n;
gets(str1);
gets(str2);
scanf(“%d”, &n);
strncpy(str2,str1,n);
2 . Stricmp Function:
This function compares the two strings. The characters of the strings may be in lower case or
upper case, the function does not discriminate between them .i.e. this function compares two
strings without the case. If the strings are same it returns the zero otherwise the non-zero value.
Char str2[20]=”hello”;
16
Syntax: stricmp(string1,string2);
#include<stdio.h>
#include<string.h>
void main()
int diff;
gets(str1);
gets(str2);
diff=stricmp(str1,str2);
if(diff==0)
else
3. Strncmp Function:
Returns non zero value i.e. the strings are different up to 2 characters.
#include<stdio.h>
#include<string.h>
void main()
int n, diff;
gets(str1);
gets(str2);
scanf(“%d”,&n);
if(diff==0)
18
else
4 .Strnicmp Function:
This function compares the characters of the two strings to a specified length. This function does
not discriminate between lowercase and uppercase letters.
#include<stdio.h>
#include<string.h>
void main()
int n, diff;
gets(str1);
gets(str2);
19
scanf(“%d”,&n);
if(diff==0)
else
5 .Strlwr Function:
Syntax: strlwr(string);
strlwr(s);
It returns hai.
#include<stdio.h>
#include<string.h>
void main()
char upper[15];
gets(upper);
}
20
6 .Strupr Function:
Syntax: strupr(string);
strupr(s);
It returns GOOD.
#include<stdio.h>
#include<string.h>
void main()
char lower[15];
gets(lower);
7 . Strdup() Function :-
This function is used for duplicating a given string at the allocated memory which is
pointed by a pointer variable.
Syntax: text2=strdup(text1);
text2=strdup(text1);
#include<stdio.h>
#include<string.h>
void main()
gets(text1);
text2=strdup(text1);
8 . Strchr() Function :-
This Function returns the pointer to position in the first Occurrence of the Character
in the given string.
Syntax: chp=strchr(string,ch);
Where string is character array, ch is character variable and chp is a pointer which collects
address returned by strchr( ) function.
chp=strchr(string,ch);
#include<stdio.h>
#include<string.h>
22
void main()
gets(string);
ch=getchar();
chp=strchr(string,ch);
if(chp)
else
9 . Strrchr() Function :-
This function returns the pointer to a position in the first occurrence of the
character in the given string from ending.
Syntax: chp=strrchr(string,ch);
10 .Strncat Function:
This will concatenate the left most n characters of text2 to the end of text1.
char s2[15]=”GURUSWAMY”;
n=4
23
/* C program to append second string with specified (n) number of characters at the end of
the first string using strncat() */
#include<stdio.h>
#include<string.h>
void main()
int n;
gets(text1);
gets(text2);
scanf(“%d”,&n);
strncat(text1, “ “);
printf(“%s \n”,text1);
}
Functions Description
strstr() Function :-
This function finds second string in the first string. It returns the pointer location
from where the second string starts in the first string. In case the first occurrence in the string is
not observed, the function returns a NULL character.
Syntax: strstr(string1,string2);
char string2[30]=”DAY”;
char *chp;
chp=strstr(string1,string2);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
clrscr();
gets(line1);
25
gets(line2);
chp=strstr(line1, line2);
if(chp)
else
Strset Function :-
This function replaces every character of a string with the symbol given by the programmer.
i.e.; the elements of the string are replaced with the arguments given by the programmer.
Syntax: strset(string,symbol);
strset(string,’y’);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
char string[15];
char symbol;
clrscr();
26
gets(string);
scanf(“%c”, &symbol);
strset(string,symbol);
Strnset Function :- This function is the same as that of strset(). Here the specified length is
provided.
Syntax: strnset(string,symbol,n);
int n=4;
strnset(string,symbol,n);
Output: ++++EFGHIJ
/* C Program to replace (set) given string with given symbol gor given number of
arguments */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
27
char string[15];
char symbol;
int n;
clrscr();
gets(string);
scanf(“%c”, &symbol);
scanf(“%d”,&n);
strnset(string,symbol,n);
Strspn Function:- This function returns the position of the string from where the source array
does not match with the target one.
Syntax: strspn(string1,string2);
strspn(str1,str2);
2) char str1[15]=”BOMBAY”;
char str2[15]=”TROMBAY”;
strspn(str1,str2);
28
/* C Program to enter 2 strings. Indicate after what character the lengths of the 2 strings
have no match */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
int length;
clrscr();
gets(str1);
puts(“Enter String2:”);
gets(str2);
length=strspn(str1,str2);
strpbrk Function :-
This function searches the first occurrence of the character in a given string and
then it displays the string starting from that character.
Syntax: strpbrk(text1,text2);
char *ptr;
29
ptr=strpbrk(text1,text2);
This function finds first occurrence of second string in the first string and returns that address
which is assigned to character pointer *ptr. The pointer ptr displays the rest string.
Output: GREAT
/*C Program to print given string from first occurrence of given character */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
char *ptr;
char text1[20],text2[20];
clrscr();
gets(text1);
gets(text2);
ptr=strpbrk(text1,text2);
printf(ptr);
Write a C program to copy one string into another without using string handling functions
#include<stdio.h>
#include<string.h>
main()
{
char s1[100], s2[100];
30
int i;
printf(“\n Enter the string : ”);
gets(s1);
i =0;
while(s1[i] ! = ‘\0’)
{
s2[i] = s1[i];
i++;
}
s2[i] = ‘\0’;
printf(“\n Copied string is : %s”, s2);
}
Write a C program to append one string to another without using string handling
functions
#include<stdio.h>
#include<string.h>
void concat(char[], char[]);
int main() {
char s1[50], s2[30];
printf("\nEnter String 1 :");
gets(s1);
printf("\nEnter String 2 :");
gets(s2);
concat(s1, s2);
printf("nConcated string is :%s", s1);
return (0);
}
void concat(char s1[], char s2[])
{
int i, j;
i = strlen(s1);
for (j = 0; s2[j] != '\0'; i++, j++) {
s1[i] = s2[j];
}
s1[i] = '\0';
}
31
Write a C program to reverse the string without using string handling functions
#include<string.h>
main()
{
char str[100], temp;
inti=0, j = 0;
printf(“\n Enter the string : ”);
gets(str);
j = strlen(str)-1;
while(i< j)
{
temp = str[j];
str[j] = str[i];
str[i] = temp;
i++;
j --;
}
printf(“\n The reversed string is”);
puts(str);
}
Write a C program to check whether two strings are identical or not (if not check which
string is higher) without using string handling functions
#include<stdio.h>
int main()
{
char str1[30], str2[30];
int i;
printf("\nEnter two strings :");
gets(str1);
gets(str2);
i = 0;
while (str1[i] == str2[i] && str1[i] != '\0')
i++;
if (str1[i] > str2[i])
printf("str1 > str2");
else if (str1[i] < str2[i])
32
The function main() in C can also accept arguments or parameters like the other
functions. It has two arguments argc(for argument count) and argv(for argument vector).It may
have one of the following two forms.
(or)
Here argc represents the number of arguments and argv is a pointer to an array of Strings
or Pointer to Pointer to Character. The argument argv is used to Pass Strings to Character.The
arguments argc and argv are called as Program Parameters. After Successful complication, The
Program is executed by using an execution command. The execution command depends on the
System running the program .It is possible to pass the values of program parameters argv through
an execution command only. Since the values are available and obtained from the command line,
they are also known as command line arguments.
cline.c
if(argc<2)
printf(“invalid options”);
getch();
exit(0);
else