0% found this document useful (0 votes)
11 views21 pages

Understanding Strings in C Programming

Uploaded by

s210859
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views21 pages

Understanding Strings in C Programming

Uploaded by

s210859
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PSTC UNIT-III Strings

3.6 Strings:
String is sequence of characters i.e letters, numbers and symbols and punctuation marks.
The string in C programming language is actually a one-dimensional array of characters which is
terminated by a null character '\0'. Since string is an array, the declaration of a string is the same as
declaring a char array. Characters are enclosed in single quotes(‘ ‘) and strings are enclosed in double
quotes(“ “).

String char [ 10];

One dimensional array

Syntax:
Data_type variable_name[size];

Char variable_name[size];

 You should not specify the datatype because string only char datatype.

char str1[20];
char str2[7] = “String”;

The following declaration creates string named “str2” and initialized with value “String”. To hold the
null character at the end of the array, the size of the character array containing the string is one more
than the number of characters in the word.

Declaration and Initialization of Strings


The following declaration and initialization create a string consisting of the word "Hello".

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Another way of Initialization is (shortcut for initializing string)


char greeting[] = "Hello";

Note: The C compiler automatically places the '\0' at the end of the string when it initializes the array.
The terminating null (‘\0’) is important, because it is the only way the functions that work with a string
can know where the string ends.

Memory Representation of String

char msg[] = "Hello";

msg

5000

Base pointer or internal pointer variable.

[Link]. Dept of CSE,IIIT-Nuzivid. Page 1


PSTC UNIT-III Strings

/* Program to demonstrate printing of a Following program illustrates printing


string */ string using ‘\0’.
int main( ) int main( )
{
char name[ ] = “Ramesh" ; char name[ ] = “Ramesh" ;
int i = 0 ; int i = 0 ;
while ( i <= 9 ) while ( name[i] != ‘\0’ )
{ {
printf ( "%c", name[i] ) ; printf ( "%c", name[i] ) ;
i++ ; i++ ;
} }
return 0; return 0;
} }

OUTPUT : OUTPUT:
Ramesh Ramesh

Note:
 To read and write string elements we need formatting specifier %s. here no need to use iterators
(loops).
 Generally, to read input from the keyboard we provide & (address operator) but to read string
we need not provide & operator because the string variable always holds the base address only,
The compiler automatically collect the all characters one by one.

Example :
#include <stdio.h>
void main( ) Beginning of End of String End of Character
{ the string array

char name[7];
printf(“enter your name); 0 1 2 3 4 5 6
scanf(“%s”,name);
printf(“\n Hi %s ,Welcome to R a m \0 \0 \0 \0
CSE”,name);
name 124 125 126 127 128 129 130
}
124
Base adreess Compiler automatically
OUTPUT: Stores the all the char of the
Enter your name: Ram String in successive memory
Hi Ram, Welcome to CSE Locations.
Cmd prompt:

Enter your name: Ram (enter)


.

 When the compiler assigns a character string to a character array, it automatically appends null
character to end of string .The size of string should be equal to maximum no of characters in
the string plus one.
 In above program, the compiler creates a character array of size 7,stores the “Ram” in it and
finally terminates the value with null character. Rest of the elements in the array are
automatically initialized to NULL.

[Link]. Dept of CSE,IIIT-Nuzivid. Page 2


PSTC UNIT-III Strings

3.6.1 Difference between character storage and String Storage:

String Character
1.
char branch[]=”CSE”;

C S E \0

Char ch=’R’;
Beginning of End of
the string String
R
2.
Char str[]=”R”;
 Here R is a character not a string.
 The character R requires only one
R \0 memory location.

 Here R is a string not a character .


 The string H requires two memory
locations one stores the character R and
another to store the null character.

3. Char str[]=””;

Empty string \0

 C permits empty string.


 it does not allow an empty character.

3.7 Functions to Read and Write Strings / Characters:


 The string can be read by three ways, i.e scanf(),gets() and getchar().the getchar function reads
the [Link] functions also called as string input functions.
 The string can be write by three ways, i.e printf(),puts() and putchar().the putchar function
prints the characters. These functions also known as string output functions

Functions

Read Write

Scanf() gets() getchar() printf() puts() putchar()

Types of String input output functions

[Link]. Dept of CSE,IIIT-Nuzivid. Page 3


PSTC UNIT-III Strings

3.7.1 getchar() and putchar() functions

 The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only single character at a time. You can use this method in the loop in case you
want to read more than one characters.
 The putchar() function prints the character passed to it on the screen and returns the same
character. This function puts only single character at a time. In case you want to display more
than one characters, use putchar() method in the loop.

#include <stdio.h>
int main( )
{
int ch;
printf("Enter a character:");
ch=getchar();
putchar(ch);
return 0;
}
When you will compile the above code, it will ask you to enter a value. When you will enter the value,
it will display the value you have entered.

3.7.2 puts() and gets() functions

 The gets() function reads a line or multiword string from stdin into the buffer pointed to by s
until either a terminating newline or EOF (end of file).
The puts() function writes the string s and a trailing newline to stdout.
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string:");
gets( str );
puts("Hello!");
puts(str);
return 0;
}
Output
Enter a string: Ramesh M
Hello! Ramesh M

3.7.3 Difference between scanf() and gets() and printf() and puts() :

[Link] scanf() gets()


1 It reads single word strings It reads multi-word strings
2 It stops reading characters when it It stops reading characters when it
encounters a whitespace encounters a newline or EOF
3 Example: Ramesh Example: Ramesh m

[Link] printf() puts()


It prints a variable with using formatting It prints a variable without using formatting
1 specifiers. specifier.
2 For new line we provide \n within printf. For new line no need provide \n.

3 Example: printf(“%s \n”,sname); Example: puts(sname);

[Link]. Dept of CSE,IIIT-Nuzivid. Page 4


PSTC UNIT-III Strings

3.8 Standard Library Character Functions:


With every C compiler a large set of useful character handling library functions are provided. For
using these functions, we need to include the header file ctype.h .

Functions Description Example

Check whether character c


isalnum(int c) is an alphanumeric or not. isalnum(‘R’);

Check whether character c


isalpha(int c) is an alphabetic or not isalpha(‘s’);

Check whether character c scanf(“%d”,&c);


iscntrl(int c) is control character or not iscntrl(c);

Check whether character c


isdigit(int c) is a digit or not isdigit(3);

Check whether character c


islower(int c) is lower case or not islower(‘s’);

Check whether character c


isupper(int c) is upper case or not isupper(‘R’);

Check whether character c


ispunct(int c) is punctuation mark or not ispunct(‘?’);

Check whether character c


isspace(int c) is a white space or not. isspace(‘ ’);

Check whether character c


isxdigit(int c) is a hexadecimal digit or not isxdigit(‘F’)

Converts the character to tolower(‘R’)


tolower(int c) lower case return r

Converts the character to toupper(‘r’)


toupper(int c) Upper case return R

Note :
 The isalpha( ) function returns nonzero if ch is a letter of the alphabet; otherwise zero is
returned.
 The isalnum( ) function returns nonzero if its argument is either a letter of the alphabet or a
[Link] the character is not alphanumeric, zero is returned.
 The iscntrl( ) function returns nonzero if ch is a control character.
 The isdigit( ) function returns nonzero if ch is a digit, that is, 0 through 9. Otherwise zero is
returned.
 The ispunct( ) function returns nonzero if ch is a punctuation character; otherwise zero is
returned.
 The isspace( ) function returns nonzero if ch is a white-space character, including space,
horizontaltab, vertical tab, formfeed, carriage return, or newline character; otherwise zero is
returned.
 The isxdigit( ) function returns nonzero if ch is a hexadecimal digit; otherwise zero is returned

[Link]. Dept of CSE,IIIT-Nuzivid. Page 5


PSTC UNIT-III Strings

Example:
#include <stdio.h>
#include <ctype.h>
int main()
{
printf("isalpha('a') : %d\n" , isalpha('a'));
printf("isalpha(34) : %d\n" , isalpha(34));
printf("isalnum('A') : %d\n" , isalnum('A') ) ;
printf("isalnum(5) : %d\n" , isalnum(5) );
char ch=’R’;
printf(“enter a character:”);
scanf(“%d”&ch);
printf("iscntrol('R') : %d\n" , iscntrl(ch)) ;
printf("isdigit('9') : %d\n" , isdigit('9'));
printf("isdigit('a') : %d\n" , isdigit('a')) ;
printf("isdigit(9) : %d\n" , isdigit(9)) ;
printf("ispunct('.') : %d\n" , ispunct('.')) ;
printf("ispunct(',') : %d\n" , ispunct(',')) ;
printf("ispunct('c') : %d\n" , ispunct('c')) ;
printf("isspace(' ') : %d\n" , isspace(' ')) ;
printf("isspace('\\t') : %d\n" , isspace('\t'));
printf("isspace('\\r') : %d\n" , isspace('\r')) ;
printf("isxdigit('F') : %d\n" , isxdigit('F')) ;
printf("tolower('A') : %c\n" , tolower('A')) ;
printf("toupper('z') : %c\n" , toupper('z')) ;
return 0;

OUTPUT :

[Link]. Dept of CSE,IIIT-Nuzivid. Page 6


PSTC UNIT-III Strings

3.9 Standard Library String Functions


With every C compiler a large set of useful string handling library functions are provided. For
using these functions, we need to include the header file string.h

Function Description

strlen() Finds length of a string

strlwr() Converts a string to lowercase

strupr() Converts a string to uppercase

strcat() Appends one string at the end of another. And strncat() upto n
strncat() characters.
strcpy() Copies a string into another and copies a string upto n
strncpy() characters
strcmp()
strncmp() Compares two strings and compare upto n numbers.

strchr()
Finds first occurrence of a given character in a string.

strrchr() finds first occurrence of a given character in a string from end.

strstr() Finds first occurrence of a given string in another string.


strrev()
Reversing of a string.
Strspn() is used to returns the index of the first character in
strspn() string that doesn’t match character in str2
strcspn() Strcspn() is used to returns the index of the first character in
string that matches of character in str2
Strtok() is used isolate sequential tokens in a terminated a null-
terminated string. these tokens are separated in the string using
strtok() delimiters.

3.9.1 strlen() function


This function counts the number of characters present in a string. Syntax for strlen() function is given
below:
size_t strlen(const char *str);

The function takes a single argument, i.e, the string variable whose length is to be found, and
returns the length of the string passed.

Note: While calculating the length it doesn’t count ‘\0’.

Example 1: C program that illustrates the usage of strlen() function.


#include<stdio.h>
#include<string.h>
int main( )
{
char str[ ] = "Ramesh" ;
int len1, len2 ;

[Link]. Dept of CSE,IIIT-Nuzivid. Page 7


PSTC UNIT-III Strings

len1 = strlen ( str ) ;


len2 = strlen ( "hello students" ) ;
printf ( "\nThe string %s length is %d", str, len1 ) ;
printf ( "\nThe string %s length is %d\n", "hello students", len2 ) ;
return 0;
}
Output
The string Ramesh length is 6
The string hello students length is 14

3.9.2 strlwr( ) and strupr( ) :


These function converts to lower to upper and upper to lower. Syntax for strlwr() and strupr()
functions given below.
Char strlwr(const char *str)
Char strlwr(const char *str)
Example 2 : C program that illustrates the usage of strlwr() and strupr()f unction.
#include<stdio.h>
#include<string.h>
int main()
{
char str1[ ] = "RGUKT" ;
printf ( "\n converting string to lower to upper case : %s", strlwr (str1)) ;
printf ( "\n converting string to Upper to lower case : %s", strupr (str1)) ;
return 0;
}
Output:
converting string to lower to upper case : rgukt
converting string to Upper to lower case : RGUKT.

3.9.3 strcpy( ) function


This function copies the contents of one string into another. Syntax for strcpy() function is given
below.
char * strcpy ( char * destination, const char * source );
Example
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.

If destination string length is less than source string, entire source string value won’t be copied into
destination string.
For example, consider destination string length is 20 and source string length is 30. Then, only 20
characters from source string will be copied into destination string and remaining 10 characters won’t
be copied and will be truncated.

Example 3: C program that illustrates the usage of strcpy() function.


#include<stdio.h>
#include<string.h>
int main()
{
char source[ ] = "Nuzivid" ;
char destination[20]= "" ;
strcpy (destination, source ) ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nDestination string = %s", destination ) ;
return 0;
}

[Link]. Dept of CSE,IIIT-Nuzivid. Page 8


PSTC UNIT-III Strings

Output
Source string = Nuzvid
Destinnation string = Nuzvid

3.9.4 strncpy( ) function

This function copies up to n characters from [Link] n is zero or negative then nothing is copied.
Syntax for strncpy( ) function is given below.

char * strncpy ( char * destination, const char * source, size_t n);

Example 4: C program that illustrates the usage of strcpy() function.


#include<stdio.h>
#include<string.h>
int main()
{
char source[ ] = "Nuzivid" ;
char destination[20]= "" ;
strcpy (destination, source,3 ) ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nDestination string = %s", destination ) ;
return 0;
}

Output
Source string = Nuzvid
Destinnation string = Nuz

3.9.5 strcat( ) function


It combines two strings. It concatenates the source string at the end of the destination string.
Syntax for strcat( ) function is given below.

char * strcat ( char * destination, const char * source );

For example, “Visakhapatanam” and “Vizag” on concatenation would result a new string
“VisakhapatnamVizag”.

Example 5: C program that illustrates the usage of strcat() function.


#include<stdio.h>
#include<string.h>
int main( )
{
char source[ ] ="Students!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nDestination string = %s", target ) ;
return 0;
}
Output
Source string = Students!
Destination string = HelloStudents!

[Link]. Dept of CSE,IIIT-Nuzivid. Page 9


PSTC UNIT-III Strings

3.9.6 strcnat( ) function


It combines two strings. It concatenates the source string at the end of the destination string up to
n character. Copying stops when n character s ae copied. Syntax for strncat( ) function is given below.

char * strncat ( char * destination, const char * source size_t n);

For example, “Vizag” and “Visakhapatam” on concatenation (upto n Characters) would result a new
string “VizagVisakha”. Here n is 7.

#include<stdio.h>
#include<string.h>
int main( )
{
char source[ ] =" Visakhapatnam " ;
char target[30] = "Vizag" ;
strncat ( target, source,7) ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nDestination string = %s", target ) ;
return 0;
}
Output
Source string = Visakhapatnam
Destination string = VizagVisakha

3.9.7 strcmp( ) and strncmp() functions


It compares two strings to find out whether they are same or different. The two strings are
compared character by character until there is a mismatch or end of one of the strings is reached,
whichever occurs first.s
 If the two strings are identical, strcmp( ) returns a value zero. If they’re not identical, it returns
the numeric difference between the ASCII values of the first non-matching pairs of characters.
 strncmp() function compares at most the first n characters of the string1 and string2.
Syntax for strcmp( ) function is given below.

int strcmp ( const char * str1, const char * str2)


int strncmp(const char *str1,const char *str2,size-t n)

Return Value from strcmp()


Return Value Description
0 if both strings are identical (equal)
<0 if the ASCII value of first unmatched character is less than second.
>0 if the ASCII value of first unmatched character is greater than second.

Note: strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.

Example 6: C program that illustrates the usage of strcmp() function.


#include<stdio.h>
#include<string.h>
int main( )
{
char string1[ ] = "Cse" ; char string2[ ] = "Ece";
int i, j, k ;
i = strcmp ( string1, "Cse" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Cse branch" ); printf ( "\n%d %d %d", i, j, k ) ;

[Link]. Dept of CSE,IIIT-Nuzivid. Page 10


PSTC UNIT-III Strings

}
Output
0 4 -32

Example 7: C program that illustrates the usage of strncmp() function.


#include<stdio.h>
#include<string.h>
int main( )
{
char string1[ ] = "Cse" ;
char string2[ ] = "Ece";
int i, j, k ;
i = strncmp( string1, "Civil",1);
j = strncmp(string2, “Eee” ,2);
k = strcmp ( string1, "Air" );
printf ( "\n%d %d %d", i, j, k ) ;
}
Output :

0 -1 1

3.9.8 strrev( ) function


this function used to reversing of a string . Syntax for strrev( ) function is given below.

char *strrev(char *string)

Example 7:Write a program to implement "strrev()" function


#include <stdio.h>
#include <string.h>
Output:
int main()
Enter any String: Ramesh
{
Reverse of String: hsemaR
char str[20];
printf("Enter any String:");
gets(str);
printf("Reverse of String:");
puts(strrev(str));
}
Example 8: Program for checking string’s palindrome property.
#include<stdio.h>
#include<string.h>
int main()
{ Output:
char str1[25],str2[25]; Enter a string: madam
int d=0; madam is palindrome
printf("\nEnter a string:");
gets(str1); Some other palindrome strings are:
strcpy(str2,str1); civic, dad, malayalam, mom,wow etc.
strrev(str1);
d= strcmp(str1,str2);
if(d==0)
printf("\n%s is pallindrome",str2);
else
printf("\n%s is not a pallindrome",str2);
return 0;
}
[Link]. Dept of CSE,IIIT-Nuzivid. Page 11
PSTC UNIT-III Strings

3.9.9 strchr( ) and strrchr() functions :


 It searches for the first occurrence of the character in the string. the function returns a pointer
pointing to the first character, or null if no match is found.
 The strrchr forSyntax for strchr( ) function is given below.

char * strchr ( char * str, int c );

Example 9: Write a program to implement "strchr()" function


#include<stdio.h>
#include<string.h>
int main()
{
char str[20]="programming In c";
char *pos;
pos=strchr(str, 'n');
if(pos)
{
printf("\n n is found in str at address posision %d",pos);
printf("\n n is found in str at index posision %d",pos-str);
}
else
{
printf( "\n n is not found in string");
}
return 0;
}

Output:
n is found string at address position 661863
n is found string at address position 9

Syntax for strrchr( ) function is given below.

char *strrchr(const char *str,int c)

Example 10 : Write a program to implement "strrchr()" function


#include<stdio.h>
#include<string.h>
int main()
{
char str[20]="programming In c";
char *pos;
pos=strrchr(str, 'n');
if(pos)
{
printf("\n n is found in str at posision %d",pos);
printf("\n n is found in str at posision %d",pos-str);
}
else
{ Output:
printf( "\n n is not found in string");
} n is found string at address position 661837
return 0; n is found string at address position 13.
}

[Link]. Dept of CSE,IIIT-Nuzivid. Page 12


PSTC UNIT-III Strings

3.9.10 strstr( ) functions :


 It searches for the first occurrence of the sub string in the string. the function returns a pointer
pointing to the first character, or null if no match is found.
 The strrchr for Syntax for strstr( ) function is given below.

char * strstr( char * str, int c );

Example11 : Write a program to implement "strstr()" function


#include <stdio.h>
#include <string.h>
int main()
{
char str1[]="HAPPY TEACHERSDAY TO ALL";
char str2[]="DAY";
char *res;
res=strstr(str1,str2);
printf("The result value:%d\n",res);
if(res)
printf("The sub string is found!!\n");
else
printf("The sub string is not found!!\n");
return 0;
}

Output:
The substring address position at 1636788
The sub string is found !!

3.9.11 strspn( ) functions :


 The function returns the index of the first character in str1 that doesn’t match any character
any character in str2.
 The for Syntax for strspn( ) function is given below.

size-t strspn(const char *str1,const char *str2);

Example 12 :Write a program to implement "strspn()" function

int main()
{
char str1[20];
char str2[20];
int count;
printf("Enter String1:");
gets(str1);
printf("Enter String2:");
gets(str2);
count=strspn(str1,str2);
printf("Similar characters occurred upto %d\n",count);
return 0;
}
Output:
Enter String1: Welcome to CSE
Enter String1: Welcome to ECE
Similar characters occurred upto 12.
[Link]. Dept of CSE,IIIT-Nuzivid. Page 13
PSTC UNIT-III Strings

3.9.12 strcspn( ) functions :


 This function returns the index of the first character in str1 that matches any character any
character in str2.
 The for Syntax for strspn( ) function is given below.

size-t strspn(const char *str1,const char *str2);

Example 13: Write a program to implement "strcspn()" function


#include <stdio.h>
#include <string.h>
int main()
{
char str1[20];
char str2[20];
int count;
printf("Enter String1:");
gets(str1);
printf("Enter String2:");
gets(str2);
count=strcspn(str1,str2);//number of characters before first occurance
printf("The first matched character:%d\n",count);
}

Enter String1: programming in c


Enter String1: in
The first matched character: 8

3.9.13 strtok( ) functions :


 This function is used isolate sequential tokens in a terminated a null-terminated string. these
tokens are separated in the string using delimiters.
 The for Syntax for strtok( ) function is given below.

char strtok(char *str1,const char *delimiter);

Example 14: Write a program to implement "strtok()" function


#include<stdio.h>
#include<string.h>
int main()
{

char str[100];
char deli[100];
char *token;
printf("Enter any string with delimiters :");
gets(str);
printf("enter delimiter :");
gets(deli);
token=strtok(str,deli);
while(res!=NULL)
{
printf("\n %s",token);
token=strtok(NULL,deli);
}

[Link]. Dept of CSE,IIIT-Nuzivid. Page 14


PSTC UNIT-III Strings

Output:
Enter any string with delimiters: ramesh,cse,iiit nuzvid,programming in c
Enter delimiters: ,
ramesh
cse
iiit nuzvid
programming in c

3.10 String manipulation without using Standard library functions:

1. Finding the length of a string.


2. Converting characters of a string into Lower to Upper case and Upper to Lower case.
3. Concatenating two Strings.
4. Comparing two Strings.
5. Reverse of a String.
6. Extracting a substring from left, right and middle.

1. Write a program to find length of a string


#include <stdio.h>
int main()
{
char str[100]; Enter string : Ramesh
int i,length=0; The length of Ramesh is : 6
printf("Enter a string:");
gets(str);
puts(str);
for(i=0;str[i]!='\0';i++)
{
length++;
}
printf("The length of the %s is: %d\n",str,length);
}

2. Write a program to convert to upper to lower case.


#include <stdio.h>
int main()
{
char str[100];
int i,length;
Output:
printf("Enter any string:");
Enter any string: ramesh
gets(str);
The string in upper case: RAMESH
for(i=0;str[i]!='\0';i++)
{
length++;
}
for(i=0;i<=length;i++)

{
if((str[i] >='a' && str[i]<='z')
str[i]=str[i]-32;
}
[Link]. Dept of CSE,IIIT-Nuzivid. Page 15
PSTC UNIT-III Strings

printf("The string in uppercase:");


puts(str);
}

3. Write a program to convert to lower to upper case.


#include <stdio.h>
int main()
{
char str[100]; Output:
int i,length; Enter any string: CSE
printf("Enter any string:"); The string in lower case: cse
gets(str);
for(i=0;str[i]!='\0';i++)
{
length++;
}
for(i=0;i<=length;i++)
{
if((int)str[i] >=65 && (int)str[i]<=90)
str[i]=str[i]+32;
}
printf("The string in lower case:");
puts(str);
}

4. Write a program to concatenating two and stores the result in new string.
#include<stdio.h>
int main()
{
char str1[100],str2[100],str3[100];
int i=0,j=0;
printf("\n enter the first string:");
gets(str1);
printf("\n enter the second string: ");
gets(str2);
while(str1[i]!='\0')
{
str3[i]=str1[i]; Output:
i++; enter the first string: Cse
j++; enter the second string : IT
} The Concatenated string is: CseIT
i=0;
while(str2[i]!='\0')
{
str3[j]=str2[i];
i++;
j++;
}
str3[j]='\0';
printf("\n The Concatenated string is :");
puts(str3);
return 0;
}

[Link]. Dept of CSE,IIIT-Nuzivid. Page 16


PSTC UNIT-III Strings

5. Write a program to concatenating (appending ) a string to another string.


#include<stdio.h>
int main()
{
char source[50],target[100];
int i=0,j=0;
printf("\n Enter the source string:");
gets(source);
printf("\n Enter the target string: ");
gets(target);
while(target[i]!='\0')
{
Output :
i++; Enter the source string: Robotics
} Enter the target string: AI &
while(source[j]!='\0') The final target string is: AI&Robotics
{
target[i]=source[j];
i++;

j++;
}
target[j]='\0';
printf("\n The final target string is :");
puts(target);
return 0;

6. Write a program to comparing two strings

#include<stdio.h>
#include<string.h>
int main()
{
char str1[50],str2[50];
int i=0,len1=0,len2=0,s=0;
printf("\nEnter the first string:");
gets(str1);
printf("\n Enter second string:");
gets(str2);
len1=strlen(str1);
len2=strlen(str2);
if(len1==len2)
{
while(i<len1)
{
if(str1[i]==str2[i])
i++;
else break;
}
if(i==len1)
{
printf("two strings are equal");
[Link]. Dept of CSE,IIIT-Nuzivid. Page 17
PSTC UNIT-III Strings

s=1;
}
}
if(len1!=len2)
{
printf("\n two strings are not equal");

}
if(s==0)
{
if(str1[i]>str2[i])
printf("\n string 1 is greater than string 2 ");
if(str1[i]<str2[i])
printf("\n string 1 is lessthan than string 2 ");
}
}

Output :
Enter the first string: Cse
Enter the second string : Cse
Two strings are equal

7. Write a program to reverse of a strings.


#include<stdio.h>
#include<string.h>
int main()
{
char str[100],temp;
int i=0,j=0;
printf("Enter a string ");
gets(str);
j=strlen(str)-1;
while(i<j)
{
temp=str[j];
str[j]=str[i];
str[i]=temp;
i++;
j--;
}
printf("the reversed string is:");
puts(str);
return 0;
}

Output :
Enter a string : cse
the reversed string is: esc

[Link]. Dept of CSE,IIIT-Nuzivid. Page 18


PSTC UNIT-III Strings

8. Write a program to extract the first N characters (Sub String ) of a string from left.
#include<stdio.h>
int main()
{
char str[50];
char sub_str[50];

int i=0,n;
printf("\n Enter a string: ");
gets(str);
printf("\nEnter no of characters to be copied: ");
scanf("%d",&n);
while(str[i]!='\0' && i<n)
Output:
{
Enter a string: Welcome to Cse
sub_str[i]=str[i];
Enter no of characters to be copied :7
i++; The Substring is: Welcome
}
sub_str[i]='\0';
printf("\n The Substring is:");
puts(sub_str);
return 0;
}

9. Write a program to extract the first N characters (Sub String ) of a string from Right.
#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
char sub_str[50];

int i=0,j=0,n;
printf("\n Enter a string: ");
gets(str);
printf("\nEnter no of characters to be copied: ");
scanf("%d",&n);
j=strlen(str)-n;
while(str[j]!='\0')
Output:
{
Enter a string: Welcome to Cse
sub_str[i]=str[j];
Enter no of characters to be copied :3
i++; The Substring is:Cse
j++;
}
sub_str[i]='\0';
printf("\n The Substring is:");
puts(sub_str);
return 0;
}

[Link]. Dept of CSE,IIIT-Nuzivid. Page 19


PSTC UNIT-III Strings

10. Write a program to extract the first N characters (Sub String) of a string from middle.
#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
char sub_str[50];

int start_pos ,i=0,m,n;


printf("\n Enter a string: ");
gets(str);
printf(“\n Enter the position from which to start the sub string :“);
scanf(“%d”&start_pos);
printf("\nEnter no of characters to be copied: ");
scanf("%d",&n);

while(str[start_pos]!='\0' && n>=0)


{
sub_str[i]=str[start_pos];
i++;
start_pos++;
n--;
}
sub_str[i]='\0';
printf("\n The Substring is:");
puts(sub_str);
return 0;
}

Output:
Enter a string: Welcome to Cse
Enter the position from to start of sub string: 8
Enter no of characters to be copied :2
The Substring is: to

3.11 Array of Strings


 String is nothing but array of characters.
 Array of strings is nothing but stores the multiple strings with single variable name. It is also
known as two dimensional (2D) array.

Syntax :

char array_name [row-size][col_size];

Here row-size indicates no of strings, column-size indicates max size of a string.

[Link]. Dept of CSE,IIIT-Nuzivid. Page 20


PSTC UNIT-III Strings

Example:

char name[4][8]={“Ram”,”IIITN”,”Cse”,”Nuzvid”};

name[0] R a m \0

name[1] I I T N \0
C s e \0
name[2]
name[3] N u z v i d \0

Memory representation of Array of string

Example: Write a program to read and print the students names.


#include<stdio.h>
int main()
{
int i=0;

char name[4][8];
while(i<4)
{
printf("\nEnter the student %d name: ",i+1);
gets(name[i]);
i++;
}
printf("\n Names of the students :");
for(i=0;i<4;i++)
{
puts(name[i]);

}
return 0;
}

Output:
Enter the student 1 name : Ram
Enter the student 2 name : Krish
Enter the student 1 name : Sree
Enter the student 2 name : Sai
Names of the students:
Ram
Krish
Sree
Sai

[Link]. Dept of CSE,IIIT-Nuzivid. Page 21

You might also like