0% found this document useful (0 votes)
38 views16 pages

Rohini 15952286220

Strings in C are represented by arrays of characters with a null character marking the end. Common string functions allow manipulating and comparing strings. Functions like strcpy, strcat, strcmp allow copying, concatenating and comparing strings.

Uploaded by

075Vishruti
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)
38 views16 pages

Rohini 15952286220

Strings in C are represented by arrays of characters with a null character marking the end. Common string functions allow manipulating and comparing strings. Functions like strcpy, strcat, strcmp allow copying, concatenating and comparing strings.

Uploaded by

075Vishruti
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
You are on page 1/ 16

ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

STRINGS:

Strings in C are represented by arrays of characters. The end of the string is marked with a
special character, the null character

• string.h : collection of functions for string manipulation.

DECLARATION OF STRINGS

• Strings are declared in a similar manner as arrays char s[5];

• Strings can also be declared using pointer


char *p;
Syntax: datatype string name[size];

char str[30];
char text[80];
STRING INITIALIZATION

char var[ ]=“hello”;

‘\0’ (NULL) charater would automatically be inserted at the end of string.

char arr[4]={‘s’,'h’,'b',’r‘,’\0’}

char arr[]={‘hello’, ‘good’ ,‘day’, ‘please’}

char Str = “abcdefg”

char greeting[] = “welcome";

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

char *c = "abcd";

char str=“100”

char str=“3.4”

Char str=“111000”

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
STRING INPUT /OUTPUT #include <stdio.h>
#include <string.h>
– printf("%s",str), scanf("%s",str) int main()
{
– gets(str),puts(str) char nickname[20];
scanf("%s", nickname);
– fgets with stdin and fputs with stdout printf("%s",nickname);
return 0;
– fgets( ) and fputs( )…for files }

Eg char s[1000] ; #include <stdio.h> #include <stdio.h>


fgets(s,1000,stdin); #include <string.h> #include <string.h>
int main() int main()
Example program { {
#include <stdio.h> char nickname[20]; char nickname[20];
int main() gets(nickname); fgets(nickname,20,stdin);
{ puts(nickname); fputs(nickname,stdout);
return 0; return 0;
char name[10];
} }
printf("Who are you? ");
fgets(name,10,stdin);
printf("Glad to meet you, %s \n",name);
return(0);
}
String input and output using fscanf() and fprintf()
C program has three I/O streams.

 stdin,
 stdout, and
 stderr

--The input stream is called standard-input (stdin); the usual output stream is called standard-
output (stdout); and the side stream of output characters for errors is called standard error
(stderr).

--Internally they represent file descriptors 0, 1, and 2 respectively.


--Calls to fprinf() and fscanf() differ significantly from calls to printf() and scanf().
--fprintf() sends formatted output to a stream and fscanf() scans and formats input from a
stream.

Example program
#include <stdio.h>
int main()
{
int fi rst, second;
fprintf(stdout,“Enter two ints in this line: ”);
fscanf(stdin,“%d %d”, &fi rst, &second);
fprintf(stdout,“Their sum is: %d.\n”, fi rst + second);
return 0;
}

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
Character Manipulation

Table: Character functions in <ctype.h> where c is the character argument


ialnum(c) Returns a non-zero if c is alphabetic or numeric
isalpha(c) Returns a non-zero if c is alphabetic
scntrl(c) Returns a non-zero if c is a control character
isdigit(c) Returns a non-zero if c is a digit, 0 – 9
isgraph(c) Returns a non-zero if c is a non-blank but printing character
islower(c) Returns a non-zero if c is a lowercase alphabetic character, i.e., a – z
isprint(c) Returns a non-zero if c is printable, non-blanks and white space included
ispunct(c) Returns a non-zero if c is a printable character, but not alpha, numeric, or blank
isspace(c) Returns a non-zero for blanks and these escape sequences: ‘\f’, ‘\n’, ‘\r’, ‘\t’, and
‘\v’
isupper(c) Returns a non-zero if c is a capital letter, i.e., A – Z
isxdigit(c) Returns a non-zero if c is a hexadecimal character: 0 –9, a – f, or A – F
tolower(c) Returns the lowercase version if c is a capital letter; otherwise returns c
toupper(c) Returns the capital letter version if c is a lowercase character; otherwise returns c

This program counts the number of words in a string converts a given text into a capital letter
#include <stdio.h>
#include <ctype.h> using toupper() function
int main() #include <stdio.h>
{ #include <sting.h>
char s[30]; int main()
int i=0,count=0;
printf(“\n enter the string\n”);
{
scanf(“%[^\n]”,s); char a[30];
while(s[i]!=‘\0’) int i=0;
{ printf(“\n enter the string\n”);
while(isspace(s[i])) gs(a);
i++;
if(s[i]!=‘\0’) while(a[i]!=‘\0’)
{ {
++count; a[i]=toupper(a[i]);
while(!isspace(s[i]) && s[i] != ‘\0’) i++;
i++;
}
}
} a[i]=‘\0’;
printf(“\n NO. of words in the string is %d:”, count); puts(a);
return 0; return 0;
} }
Output: Output:
enter the string
enter the string
how are you
how
NO. of words in the string is
HOW
3

Disadvantage : C has the weakest character string capability. Strictly speaking, there are no
character strings in C, just arrays of single characters.

What character manupilation cannot do


o Assign one to the other: s1 = s2;
o Compare them for collating sequence: s1 < s2
o Concatenate them to form a single longer string: s1 + s2
o Return a string as the result of a function

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

String Manipulation

A set of standard C library functions that are contained in <string.h> provides the following.

Function Description
strcpy(s1,s2) Copies s2 into s1
strncpy(s1,s2,n) It copies first n characters of str2 into str1.
strcat(s1,s2) Concatenates s2 to s1. That is, it appends the string contained by s2 to
the end of the string pointed to by s1. The terminating null character
strncat(s1,s2,n) First n characters of str2 is concatenated at the end of str1
strlen(s1) Returns the length of s1. That is, it returns the number of characters in
the string without the terminating null character.
strcmp(s1,s2) Returns 0 if s1 and s2 are the same
Returns less than 0 if s1<s2
Returns greater than 0 if s1>s2
strncmp(s1,s2,n) Returns 0 if s1 and s2 are the same for first n characters
strcmpi( ) Same as strcmp() function. But, this function negotiates case. “A”
and “a” are treated as same.
strchr(s1,ch) Returns pointer to first occurrence ch in s1
strrchr(s1,ch ) Returns pointer tolast occurrence ch in s1
strstr(s1,s2) Returns pointer to first occurrence s2 in s1
strlen( ) function in C gives the length of the given string
strdup( ) function in C duplicates the given string
strlwr( ) function converts a given string into lowercase
strupr( ) function converts a given string into uppercase
strrev( ) function reverses a given string in C language

strcat ( str1, str2 ) Source string = APPLE strncat ( str1, str2, n ) Source string = APPLEJUICE
#include <stdio.h> Target string = LIME #include <stdio.h> Target string = LIME
#include <string.h> Target string after strcat( ) = #include <string.h> Target string after strcat( ) =
int main( ) LIME APPLE int main( ) LIME APPL

{ char source[ ] = " APPLEJIUCE" ;


char source[ ] = " APPLE" ; char target[ ]= “LIME" ;
char target[ ]= " LIME" ; printf ( "\nSource string = %s", source ) ;
printf ( "\nSource string = %s", source ) ; printf ( "\nTarget string = %s", target ) ;
printf ( "\nTarget string = %s", target ) ; strncat ( target, source, 4 ) ;
strcat ( target, source ) ; printf ( "\nTarget string after strncat( ) = %s", target )
printf ( "\nTarget string after strcat( ) = %s", target ) ; ;
return 0; return 0;}
}

strcpy(str2,str1) source string = one strcpy(str2,str1,n) source string = mindblowing


#include <stdio.h> target string #include <stdio.h> target string =
#include <string.h> target string after strcpy( ) = one #include <string.h> target string after strncpy( ) =
int main( ) int main( ) mindb
{ {
char source[ ] = "fresh2refresh" ; char source[ ] = “mindblowing" ;
char target[20]= "" ; char target[20]= "" ;
printf ( "\n source string = %s", source ) ; printf ( "\n source string = %s", source ) ;
printf ( "\n target string = %s", target ) ; printf ( "\n target string = %s", target ) ;
strcpy ( target, source ) ; strncpy ( target, source, 5 ) ;
printf ( "\n target string after strcpy( ) = %s", target ) ; printf ( "\ntarget string after strcpy( ) = %s", target ) ;
return 0; return 0;}
}

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
strlen( ) strcmp(str1,str20 strcmp(str1, str2)
#include <stdio.h> string length = #include <stdio.h> = 32
#include <string.h> 6 #include <string.h> strcmp(str1, str3)
int main( ) int main() = 0 (same)
{ {

int len; char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";


char str[20]=“APPLE" ; int result;
len = strlen(str) ; result = strcmp(str1, str2);
printf ( "\string length = %d \n" , len ) ; printf("strcmp(str1, str2) = %d\n", result);
return 0; result = strcmp(str1, str3);
} printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
strchr(str,ch ) first occurrence of strrchr(str,ch ) Last occurrence of
character “i” in This is a character “i” in This is
#include <stdio.h> string for testing” is 3 #include <stdio.h> a string for testing” is
#include <string.h> #include <string.h> 26
int main () int main ()
{ {
char string[55] ="This is a string for testing";
char string[55] ="This is a string for testing"; char *p;
char *p; p = strrchr (string,'i');
p = strchr (string,‘i'); printf ("Last occurrence of character "i" in "%s
printf ("First occurrence of character "i" in %s " is”, string, p);
is” %s, string, p); return 0;
return 0; }
}

strlwr( ) Output: strupr( )


Output:
modify this MODIFY THIS STRING TO
#include<stdio.h> string to lower #include<stdio.h>
#include<string.h> #include<string.h> UPPER
int main() int main()
{ {
char str[ ] = "MODIFY This String To char str[ ] = "Modify This String To Upper";
LOwer"; printf("%s\n",strupr(str));
printf("%s\n",strlwr (str)); return 0;
return 0; }
}

strrev( ) OUTPUT strset( ) Original string is : Test String


String before strrev( ) : Hello Test string after strset() :
#include<stdio.h> String after strrev( ) : olleH #include<stdio.h> ###########
#include<string.h> #include<string.h>
int main() int main()
{ {
char name[30] = "Hello"; char str[20] = "Test String";
printf("String before strrev( ): %s\n",name); printf("Original string is : %s", str);
printf("String after strrev( ) : %s",strrev(name)); printf("Test string after strset() : %s",strset(str,'#'));
return 0; printf("After string set: %s",str);
} return 0;
}

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

Conversion functions

Typecast Function Description


atoi( ) Converts string to integer
atof( ) Converts string to float
atol( ) Converts string to long
itoa( ) Converts integer to string
ltoa( ) Converts long to string

atoi function atof function itoa( )-Converts integer to string


#include <stdio.h> #include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h> #include <stdlib.h> Output:
int main() #include <string.h> Binary value =
int main() { int main() 1101010000110101
{ char a[10] = "3.14"; { Decimal value = 54325
char a[10] = "100"; float pi = atof(a); int a=54325; Hexadecimal value = D435
int value = atoi(a); printf("Value of pi = %f\n", char buffer[20];
printf("Value = %d\n", value); pi); itoa(a,buffer,2);
return 0; return 0; printf("Binary value = %s\n", buffer);
} } itoa(a,buffer,10);
Output: Output: printf("Decimal value = %s\n", buffer);
Value = 100 Value of pi = 3.140000 itoa(a,buffer,16);
printf("Hexadecimal value = %s\n", buffer);
return 0;
SCANSET }

• This conversion facility allows the programmer to specify the set of characters that are (or
are not) acceptable as part of the string.

• A scanset conversion consists of a list of acceptable characters enclosed within square


brackets.

Program-1 Program-2
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
char str[50]; char str[50];
printf(“Enter a string in lower case:”); printf(“Enter a string in lower case:”);
scanf(“%[a-z]”,str); scanf(“%[^a-z]”,str); printf(“The
printf(“The string was : %s\n”,str); string was : %s\n”,str);return 0;
return 0; }
} Output
Enter a string in lower case: abcd1234
Output The string was : 1234
(a) Enter a string in lower case: hello world
The string was: hello world

(b) Enter a string in lower case: hello, world


The string was: hello
[In the second case, the character, ‘,’ (comma)
is not in the specified range.]

(c) Enter a string in lower case: abcd1234


The string was : abcd
[In the third case, the digit 1234 is not in
the specified range.]

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

STRING ARRAY [ONE DIMENTIONAL ]

CHAR/STRING ARRAY DECLARATION


String array are one-dimensional array of characters terminated by a null character '\0'.
 Character Array
char arr[]={‘s’,'h’,'b',’r'}
char arr[]={‘hello’, ‘good’ ,‘day’, ‘please’}
char Str = “abcdefg”
char greeting[] = "Hello";
char greeting[6] = {'H', 'e', 'l', 'l', 'o'};

String Array
 String Array = {“abc”, ”def”, “ghi”}

STRING ARRAY [TWO DIMENTIONAL ]

Declaration of a two-dimensional array of strings.


A two-dimensional array of strings can be declared as follows:
<data_type> <string_array_name>[<row_size>][<columns_size>];

char s[5][30];

Initialization

Two-dimensional string arrays can be initialized as shown

char s[5][10] ={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”};

which is equivalent to

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

Example program : Search a character in a string


#include<stdio.h>
int main() { Enter a string: apple lime juice
char str[20], ch;
Enter the character to be searched : i
int count = 0, i;
printf("\nEnter a string : ");
Character i is present
scanf("%s", &str);

printf("\nEnter the character to be searched : ");


scanf("%c", &ch);

for (i = 0; str[i] != '\0'; i++) {


if (str[i] == ch)
count++;
}
if (count == 0)
printf("\n Character '%c'is not present", ch);
else
printf("\n Character '%c'is present", ch);
return 0;
}

binary search for strings


#include <stdio.h>
#include <string.h>
void main()
enter the number of names to be added
{
int i,n,low,high,mid; 4
char a[50][50],key[20]; enter the name in ascending order
printf("enter the number of names to be added\n"); mango
scanf("%d",&n); jackfruit
printf("enter the name in ascending order\n"); apple
for(i=0;i<=n-1;i++)
grapes
{
scanf("%s",&a[i]); enter the name to be searched
} oranges
printf("\n"); name not found
printf("enter the name to be searched\n");
scanf("%s",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if (strcmp(key,a[mid])==0)
{
printf("key found at the position %d\n",mid+1);
exit(0);
}
else if(strcmp(key,a[mid])>0)
{
high=high;
low=mid+1;
}
else
{
low=low;
high=mid-1;
}
}
printf("name not found\n");
}

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
Program to Sort String Characters in string
#include <stdio.h>
#include <string.h>
int main (void) {
char string[] = "simplyeasylearning"; OUTPUT
char temp; String before sorting - simplyeasylearning
String after sorting - aaeegiillmnnprssyy
int i, j;
int n = strlen(string);

printf("String before sorting - %s \n", string);

for (i = 0; i < n-1; i++) {


for (j = i+1; j < n; j++) {
if (string[i] > string[j]) {
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
}
}
printf("String after sorting - %s \n", string);
return 0;
}
program to sort the names of students.
#include <stdio.h>
#include <string.h>
int main()
{
char names[5][10], temp[10];
int i, n, j;
clrscr();
printf("\n Enter the number of students : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n Enter the name of student %d : ", i+1);
scanf(“%s”,&names[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n–i–1;j++)
{
if(strcmp(names[j], names[j+1])>0)
{
strcpy(temp, names[j]);
strcpy(names[j], names[j+1]);
strcpy(names[j+1], temp);
}
}
}
printf("\n Names of the students in alphabetical order are : ");
for(i=0;i<n;i++)
{ printf(“%s \n”,names[i]);
}
return 0;
}
Output
Enter the number of students : 3
Enter the name of student 1 : Goransh
Enter the name of student 2 : Aditya
Enter the name of student 3 : Sarthak
Names of the students in alphabetical order are :
Aditya
Goransh
Sarthak

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
Length of String Without Using strcat( )

#include <stdio.h>
int main()
{
char s[1000], i;

printf("Enter a string: ");


scanf("%s", s);

for(i = 0; s[i] != '\0'; ++i);

printf("Length of string: %d", i);


return 0;
}
Output

Enter a string: apple


Length of string: 5

copy Two Strings Without Using strcpy( )


Output

#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);
for(i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}

Enter String s1: apple


String s2: apple

program to convert the lower case characters of a string into upper case without using string
functions

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
#include <stdio.h>
int main()
{ Output
char str[100], upper_str[100]; Enter the string : Hello
The string converted into upper case is : HELLO
int i=0;
clrscr();
printf("\n Enter the string :");
gets(str);
while(str[i] != '\0')
{
if(str[i]>='a' && str[i]<='z')
upper_str[i] = str[i] – 32;
else
upper_str[i] = str[i];
i++;
}
upper_str[i] = '\0';
printf("\n The string converted into upper case is : ");
puts(upper_str);
return 0;
}
program to compare two strings without using string function
#include <stdio.h>
#include <string.h>
int main()
{
char str1[50], str2[50];
int i=0, len1=0, len2=0, same=0;
clrscr();
printf("\n Enter the first string : ");
gets(str1);
printf("\n Enter the 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)
{
same=1;
printf("\n The two strings are equal");
}
}
if(len1!=len2)
printf("\n The two strings are not equal");
if(same == 0)
{
if(str1[i]>str2[i])
printf("\n String 1 is greater than string 2");
else if(str1[i]<str2[i])
printf("\n String 2 is greater than string 1");
}
return 0;
}
Write a program to reverse a given string without using string function
#include <stdio.h>

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
#include <conio.h>
#include <string.h>
int main() Output
{ Enter the string: Hi there
char str[100], reverse_str[100], temp; The reversed string is: ereht iH
int i=0, j=0;
clrscr();
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);
getch();
return 0;
}
C program to change case from upper to lower and lower to upper without using string function
#include <stdio.h>
int main ()
{ o/p
int i = 0; Input a string
char ch, s[1000]; file ABC
the string is
printf("Input a string\n"); FILEabc
gets(s);

while (s[i] != '\0') {


ch = s[i];
if (ch >= 'A' && ch <= 'Z') // convrt to lower case
s[i] = s[i] + 32;
else if (ch >= 'a' && ch <= 'z') //convert to upper case
s[i] = s[i] - 32;
i++;
}
Printf(“\n the string is:”)
printf("%s\n", s);
return 0;
}
C Program to Count Number of Words in a given Text or Sentence
#include <stdio.h>
#include <string.h>
void main() o/p
{ enter the string
char s[200]; hello how are you friends
int count = 0, i; number of words in given string are: 5
printf("enter the string\n");
scanf("%[^\n]s", s);
for (i = 0;s[i] != '\0';i++)
{ if (s[i] == ' ')
count++; }
printf("number of words in given string are: %d\n", count + 1);
return 0;
}
Palindrome program in C language using built in functions

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
#include <stdio.h>
#include <string.h>
o/p
int main()
Enter a string to check if it is a palindrome
{
wow
char a[100], b[100];
Entered string is a palindrome
printf("Enter a string to check if it is a palindrome\n");
gets(a);
strcpy(b,a);
strrev(b);
if (strcmp(a,b) == 0)
printf("Entered string is a palindrome.\n");
else
printf("Entered string isn't a palindrome.\n");
return 0;
}
Palindrome program in C language without using built in functions
#include <stdio.h>
#include <string.h>
int main(){
char string1[20]; o/p
int i, length; Enter a string:wow
int flag = 0; wow is not a palindrome
printf("Enter a string:");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++){
if(string1[i] != string1[length-i-1]){
flag = 1;
break;
}}
if (flag) {
printf("%s is not a palindrome", string1);
}
else {
printf("%s is a palindrome", string1);
}
return 0;
}
C program to find the frequency of characters in a string
#include <stdio.h> Enter a string
#include <string.h> maple tree
int main() a occurs 1 times in the string
{ e occurs 3 times in the string
char string[100]; l occurs 1 times in the string
int c = 0, count[26] = {0}, x; m occurs 1 times in the string
printf("Enter a string\n"); p occurs 1 times in the string
gets(string); r occurs 1 times in the string
while (string[c] != '\0') { t occurs 1 times in the string
/** Considering characters from 'a' to 'z'
only and ignoring others. */
if (string[c] >= 'a' && string[c] <= 'z') {
x = string[c] - 'a';
count[x]++;
}
c++;
}
for (c = 0; c < 26; c++)
printf("%c occurs %d times in the string.\n", c + 'a', count[c]);
return 0; }

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
C program to swap two strings
#include <stdio.h>
#include <string.h>
int main()
{
char first[100], second[100], temp[100];

printf("Enter first string\n");


gets(first);

printf("Enter second string\n");


gets(second);

printf("\nBefore Swapping\n");
printf("First string: %s\n", first);
printf("Second string: %s\n\n", second);

strcpy(temp, first);
strcpy(first, second);
strcpy(second, temp);

printf("After Swapping\n");
printf("First string: %s\n", first);
printf("Second string: %s\n", second);

return 0;
}
Write a program to extract a substring from the middle of a given string.
#include <stdio.h>
#include <conio.h>
int main()
{
char str[100], substr[100];
int i=0, j=0, n, m;
clrscr();
printf("\n Enter the main string : ");
gets(str);
printf("\n Enter the position from which to start the substring: ");
scanf("%d", &m);
printf("\n Enter the length of the substring: ");
scanf("%d", &n);
i=m;
while(str[i] != '\0' && n>0)

substr[j] = str[i];
i++;
j++;
n––;
}
substr[j] = '\0';
printf("\n The substring is : ");
puts(substr);
getch();
return 0;
}
Output
Enter the main string : Hi there
Enter the position from which to start the substring: 1
Enter the length of the substring: 4
The substring is : i th

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
Write a program to insert a string in the main text.
#include <stdio.h>
int main()
{
char text[100], str[20], ins_text[100];
int i=0, j=0, k=0,pos;
clrscr();
printf("\n Enter the main text : ");
gets(text);
printf("\n Enter the string to be inserted : ");
gets(str);
printf("\n Enter the position at which the string has to be inserted: ");
scanf("%d", &pos);
while(text[i]! = '\0')
{
if(i==pos) Output
{ Enter the main text : newsman
while(str[k] != '\0') Enter the string to be inserted : paper
{ Enter the position at which the string has to be
ins_text[j] = str[k]; inserted: 4
j++; The new string is: newspaperman
k++;
}
}
else
{
ins_text[j] = text[i];
j++;
}
i++;
}
ins_text[j] = '\0';
printf("\n The new string is : ");
puts(ins_text);
getch();
return0;
}
Write a program to delete a substring from a text.
#include <stdio.h>
int main()
{
char text[200], str[20], new_text[200]; Output
int i=0, j=0, found=0, k, n=0, copy_loop=0; Enter the main text : Hello, how are you?
clrscr(); Enter the string to be deleted : , how are
printf("\n Enter the main text : "); you?
gets(text); The new string is : Hello
printf("\n Enter the string to be deleted : ");
gets(str);
while(text[i]!='\0')
{
j=0, found=0, k=i;
while(text[k]==str[j] && str[j]!='\0')
{
k++;
j++;
}
if(str[j]=='\0')
copy_loop=k;
new_text[n] = text[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]='\0';
printf("\n The new string is : ");
puts(new_str);
return 0;

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C


ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
}
Write a program to replace a pattern with another pattern in the text.
#include <stdio.h>
#include <conio.h>
main()
{
char str[200], pat[20], new_str[200], rep_pat[100];
int i=0, j=0, k, n=0, copy_loop=0, rep_index=0;
clrscr();
printf("\n Enter the string : ");
gets(str);
printf("\n Enter the pattern to be replaced: ");
gets(pat);
printf("\n Enter the replacing pattern: ");
gets(rep_pat);
while(str[i]!='\0')
{
j=0,k=i;
while(str[k]==pat[j] && pat[j]!='\0')

{
k++;
j++;
}
if(pat[j]=='\0')
{
copy_loop=k;
while(rep_pat[rep_index] !='\0')
{
new_str[n] = rep_pat[rep_index];
rep_index++;
n++;
}
}
new_str[n] = str[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]='\0';
printf("\n The new string is : ");
puts(new_str);
getch();
return 0;
}
Output
Enter the string : How ARE you?
Enter the pattern to be replaced : ARE
Enter the replacing pattern : are
The new string is : How are you?

UNIT-1 EC8393-FUNDAMENTALS OF DATA STRUCTURES IN C

You might also like