Wednesday, April 13, 2022

Assignment 3: String handling in C and standard library functions for strings

 Assignment 3:   String handling in C and standard library functions for strings

  • A string is an array of characters terminated by a special character called NULL character(\0). 
  • Each character is stored in 1 byte as its ASCII code. 
  • An array of strings is a two dimensional array of characters. 
  • It can be treated as a 1-D array such that each array element is a string.

Declaring Strings:-
 char string_name[size]; char str[80];

Initializing Strings:-
char str[]= { ’G’, ’o’, ’o’,
d’,’\0’ };
char str [ ] = “Hello”;

Accepting Strings:-
scanf and gets can be used to accept strings

 char name[20], address[50];
printf(“\n Enter your name”);
scanf(“%s”,name);
printf(“\n Enter your address”);
gets(address);

Displaying Strings:-
printf and puts can be used to display strings. 

Printf(“\n The name is %s:”,name);
printf(“\n The address is :”);
puts(address);

Declaring String array:-
char array[size1][size2];
 char cities[4][10];

Initializing String array:-
char cities[4][10] = { “Pune”,“Mumbai”,“Delhi”, “Chennai”} ;

All string operations are performed using functions in “string.h”. Some of the most commonly used functions are
a. strlen(str) – Returns the number of characters in the string (excluding \0)
b. strcpy(deststr, srcstr) – Copies one string to another
c. strcmp(str1,str2) – Compares two strings. Returns 0 (equal), +ve (first string > second), -ve (first string <second ). It is casesensitive.
d. strcmpi(str1,str2) – Same as strcmp but ignores case
e. strcat(str1,str2) – Concatenates the second string to the first. Returns the concatenated string.
f. strchr(str1, ch) – truncate the string before first occurrence of character in the string.
g. strrchr(str1,ch) –truncate the string before last occurrence of character in the string.


Examples:-
Sample program 1)

#include <string.h>
main( )
{
char str1[30],str2[30],str3[60];
printf(“\nEnter the first string:”);
gets(str1);
printf(“\n Enter the second string string:”);
gets(str2);
if (strlen(str1) == strlen(str2))
{ strcpy(str3,strrev(str1));
strcat(str3,str2);
 puts(str3);
}
else
{ strcat(str1,str2);
 puts(str1);
 }
}

Sample Program 2)

#include <stdio.h>
main( )
{
charlist[10][20]; /*list is an array of 10 strings*/
charname[20];
int i,n;
printf(“\n How many names ?:”);
scanf(“%d”, &n);
/* Accepting n names */
for (i=0;i<n; i++)
{
printf(“\n Enter name %d,”i);
gets(list[i]);
}
printf(“\n Enter the name to be searched “);
gets(name);
for (i=0; i<n; i++)
{
if(strcmp(list[i],name)==0)
 break;
}
if(i==n)
printf(“Name is in list\n”);
else
printf(“Name is not in list\n”);
}


1. Write a program to read a string and copy it to another sting and display copied string.
Also the length of copied string. (Use built in functions)
Program:-
#include <string.h>
 
int main()
{
   char s1[1000],s2[1000];  
    int i;
 
    printf("Enter any string: ");
    gets(s1);
    strcpy(s2,s1);
    printf("original string s1='%s'\n",s1);
    printf("copied string   s2='%s'",s2);
     printf("Length of copied string  =%d",strlen(s2));
    return 0;
    
}

2. Write a program to read two strings. If first string is greater than second then
concatenate second to first and display concatenated string, If first string is smaller than
second then concatenate first to second, other-wise display length of string. (use strcmp)
Program:-

#include <string.h>
main( )
{
char str1[30],str2[30],str3[60]; 
printf("\nEnter the first string:");
gets(str1);
printf("\n Enter the second string string:");
gets(str2);

if(strcmp(str1,str2) >= )
{
   strcat(str1,str2); 
printf("concatenated string ='%s'",str1);
}
else
{
  strcat(str2,str1) ;
printf("concatenated string ='%s'",str2);
}


}

3. Write a program to read a string and one character. Check whether given character is
present in the given string or not? (Hint: use strchr or strrchr)
Program:-
#include <stdio.h>
#include <string.h>
 
#define SIZE 40
 
int main(void)
{
  char buf[SIZE];
  char * ptr;
  int    ch ;
 
printf("\nEnter the first string:");
gets(str1);

    printf("\nEnter the Character:");
scanf("%c",&ch);

  /* This illustrates strchr */
  ptr = strchr( buf, ch );
  printf( "The first occurrence of %c in '%s' is '%s'\n", ch, buf, ptr );
 
  /* This illustrates strrchr */
  ptr = strrchr( buf, ch );
  printf( "The last occurrence of %c in '%s' is '%s'\n", ch, buf, ptr );
}



1. Write a program which accepts a sentence from the user and alters it as follows: Every space is replaced by *, case of all alphabets is reversed, digits are replaced by ?.
Program:-
#include<stdio.h>
#include<ctype.h>
#include<string.h>
void Stral(char str[])
{
 int i;

 // To replace space by * in sentence
 for(i=0;i<=strlen(str)-1;i++)
 {
 if(str[i]==' ')
  str[i]='*';

 // To change the case of alphabets in sentence
 if(islower(str[i]))
  str[i]=toupper(str[i]);
 else
  str[i]=tolower(str[i]);

 // To replace digits by ? in sentence
 if(isdigit(str[i]))
  str[i]='?';
 }

 printf("\n %s \n",str);
}

void main()
{
 char str[100];
 printf("\n Enter any sentence:-");
 fgets(str,100,stdin);
 Stral(str);
}


2. Write a program which accepts a sentence from the user. Find and display reverse of it.
(Don’t use any function).
Program:-
#include <stdio.h>
void reverse();
void main()
{
    printf("Please enter a sentence: ");
    reverse();
}

void reverse()
{
    char c;
    scanf("%c", &c);
    if (c != '\n') {
        reverse();
        printf("%c", c);
    }
}

3. Write a program that accepts n words and outputs them in dictionary order.
Program:-
/*  C Program to Sort strings Lexicographically (Dictionary Order)  */

#include<stdio.h>
#include <string.h>

int main()
{
    int i, j;
    char str[10][50], temp[50];

    printf("\nEnter 10 words:: \n");

    for(i=0; i<10; ++i)
        scanf("%s[^\n]",str[i]);


    for(i=0; i<9; ++i)
        for(j=i+1; j<10 ; ++j)
        {
            if(strcmp(str[i], str[j])>0)
            {
                strcpy(temp, str[i]);
                strcpy(str[i], str[j]);
                strcpy(str[j], temp);
            }
        }

    printf("\nIn lexicographical order: \n");
    for(i=0; i<10; ++i)
    {
        puts(str[i]);
    }

    return 0;
}



1. Write a program that accepts a string and displays it in the shape of a kite. Example:
“abc” will be displayed as:
    a
   a a
 a b a b
a b c a b c
 a b a b
   a a
    a

Program:-

#include<stdio.h>
#include<string.h>
#include<string.h>
 
int main()
{
      char string[100];
      int c, i, length;
 
      printf("\n Enter a string : ");
      gets(string);
 
      length = strlen(string);
      printf("\n");
 
      for ( c = 0 ; c < length ; c++ )
      {
          printf(" ");
          for( i = 0 ; i <= c ; i++ )
          {
 
               printf("%c", string[i]);
          }
          printf("\n");
      }
    for ( c = length ; c >=0 ; c-- )
      {
          printf(" ");
          for( i = 0 ; i <= c ; i++ )
          {
 
               printf("%c", string[i]);
          }
          printf("\n");
      }
 
      return 0;
}
 

2. Write a program that accepts a string and generates all its permutations. For example:
ABC, ACB, BAC, BCA, CAB,CBA
Program:-

#include <stdio.h>
#include <string.h>
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
 

void permutation(char *a, int l, int r)
{
    int i;
    if (l == r)
        printf("%s\n", a);
    else
    {
        for (i = l; i <= r; i++)
        {
            swap((a + l), (a + i));
            permutation(a, l + 1, r);
 
            swap((a + l), (a + i));
        }
    }
}
 

int main()
{
    char str[20];
    printf("\n Enter any string:");
   gets(str);
    int n = strlen(str);
    permutation(str, 0, n-1);
    return 0;


3. Write a menu driven program to perform the following operations on strings using
standard library functions:
1.Length 2. Copy 3.Concatenation 4. Compare 
Program:-
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    char str1[20],str2[20];
    int ch,i,j;
    do
    {
        printf("\tMENU");
        printf("\n------------------------------\n");
        printf("1:Find Length of String");
        printf("\n2:Find Reverse of String");
        printf("\n3:Concatenate Strings");
        printf("\n5:Copy String ");
        printf("\n5:Compare Strings");
        printf("\n6:Exit");
        printf("\n------------------------------\n");
        printf("\nEnter your choice: ");
        scanf("%d",&ch);
        switch(ch)
        {
            case 1:
                printf("Enter String: ");
                scanf("%s",str1);
                i=strlen(str1);
                printf("Length of String : %d\n\n",i);
            break;
            case 2:
                printf("Enter String: ");
                scanf("%s",str1);
                //strrev(str1);
                printf("Reverse string : %s\n\n",str1);
            break;
            case 3:
                printf("\nEnter First String: ");
                scanf("%s",str1);
                printf("Enter Second string: ");
                scanf("%s",str2);
                strcat(str1,str2);
                printf("String After Concatenation : %s\n\n",str1);
            break;
            case 4:
                printf("Enter a String1: ");
                scanf("%s",str1);
                printf("Enter a String2: ");
                scanf("%s",str2);
                printf("\nString Before Copied:\nString1=\"%s\",String2=\"%s\"\n",str1,str2);
                strcpy(str2,str1);
                printf("-----------------------------------------------\n");
                printf("\"We are copying string String1 to String2\" \n");
                printf("-----------------------------------------------\n");
                printf("String After Copied:\nString1=\"%s\", String2=\"%s\"\n\n",str1,str2);
            break;
            case 5:
                printf("Enter First String: ");
                scanf("%s",str1);
                printf("Enter Second String: ");
                scanf("%s",str2);
                j=strcmp(str1,str2);
                if(j==0)
                {
                    printf("Strings are Same\n\n");
                }
                else
                {
                    printf("Strings are Not Same\n\n");
                }
            break;
            case 6:
                exit(0);
            break;
            default:
                printf("Invalid Input. Please Enter valid Input.\n\n ");
        }
    }while(ch!=6);
    return 0;
}



  2. Write a program that will accept a string and character to search. The program will call a function, which will search for the occurrence position of the character in the string and return its position. Function should return –1 if the character is not found in the string. 

/* C Program to find First Occurrence of a Character in a String */
 
#include <stdio.h>
#include <string.h>

int Find_FirstCharcater(char str[], char ch);

int main()
{
  char str[100], ch;
  int index;
 
  printf("\n Please Enter any String :  ");
  gets(str);
 
  printf("\n Please Enter the Character that you want to Search for :  ");
  scanf("%c", &ch);
 
  index = Find_FirstCharcater(str, ch); 
 
    if(index == -1)
  {
  printf("\n Sorry!! We haven't found the Search Character '%c' ", ch);
}
else
{
printf("\n The First Occurrence of the Search Element '%c' is at Position %d ", ch, index + 1);
}
  return 0;
}

int Find_FirstCharcater(char str[], char ch)
{
int i;
for(i = 0; str[i] != '\0'; i++)
{
if(str[i] == ch)
{
return i;
}  
}
return -1;
}


 #include <stdio.h>
#include <string.h>
 
void check(char *s,char c)
{
    int i;
     for(i=0;s[i];i++)  
    {
    if(s[i]==c)
    {
    printf("character '%c' found at location: %d\n ",c,i);
 
}
  }
  
 }
int main()
{
 
    char s[1000],c;  
  
    printf("Enter  the string : ");
    gets(s);
    printf("Enter character to be searched: ");
    c=getchar();
    check(s,c);
    
return 0;
     
}


3. A palindrome is a string that reads the same-forward and reverse. Example: “madam” is a Palindrome. Write a function which accepts a string and returns 1 if the string is a palindrome and 0 otherwise. Use this function in main. 
#include <stdio.h>
#include <string.h>

void isPalStrFind(char str[]);
 
int main()
{
  char str[100];
    printf("\n Please Enter any Text :  ");
  gets(str);
  isPalStrFind(str);
return 0;
}

void isPalStrFind(char str[])
{
int i = 0;
int len = strlen(str) - 1;
while (len > i)
{
if(str[i++] != str[len--])
{
printf("\n %s is Not", str);
return;
}
}
printf("\n %s is a Palindrome String", str);
}

4. Write a program which accepts a sentence from the user and alters it as follows: Every space is replaced by *, case of all alphabets is reversed, digits are replaced by ? 
Program:-
#include<stdio.h>
#include<ctype.h>
#include<string.h>
void Stral(char str[])
{
int i;
// To replace space by * in sentence
for(i=0;i<=strlen(str)-1;i++)
{
if(str[i]==' ')
 str[i]='*';
// To change the case of alphabets in sentence
if(islower(str[i]))
 str[i]=toupper(str[i]);
else
 str[i]=tolower(str[i]);
// To replace digits by ? in sentence
if(isdigit(str[i]))
 str[i]='?';
}
printf("\n %s \n",str);
}
void main()
{
char str[100];
printf("\n Enter any sentence:-");
fgets(str,100,stdin);
Stral(str);
}

Set B . Write C programs for the following problems.
1. Write a program that accepts n strings and displays the longest string.
#include<stdio.h>
#include<string.h>
#define size 100 
#define wsize 20
void Longest_Word(char str[][20],int n); // Longest_Word Function Prototype
void main()
{
char str[size][wsize];
int i,count=0,n;
printf("\n How many words to accept:- ");
scanf("%d",&n);
printf("\n Enter %d words:- \n \n",n);
for(i=0;i<n;i++)
scanf("%s",str[i]);
Longest_Word(str,n);
}
// Longest_Word Function
void Longest_Word(char str[][20],int n)
{
int i,Max,len1,c;
Max=strlen(str[0]);
for(i=1;i<n;i++)
{
len1=strlen(str[i]);
if(len1>Max)
{
c=i;
Max=len1;
}
}
printf("\n The longest string among all is \"%s\" \n \n",str[c]);
}

2. Define two constant arrays of strings, one containing country names (ex: India, France etc) and the other containing their capitals. (ex: Delhi, Paris etc). Note that country names and capital names have a one-one correspondence. Accept a country name from the user and display its capital.
Example: Input: India , Output: Delhi.
Program:-
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdio.h>
void main()
{
char country[6][20]={"India","Canada","Rome","France","Jarmany","Chaina"}, capital[6]
[20]={"Delhi","ottawa","Italy","Paris","Barlin","Bijing"}, srch[20];
int i,j, flag=0, p;
printf("Country Capital\n");
for(i=0;i<6;i++)
{
 printf("%s %s\n",country[i],capital[i]);
}
printf("\n\nEnter any country to get its capital name: ");
gets(srch);
for(i=0;i<6;i++)
{
 if(strcmp(srch,country[i])==0)
 {
 flag++;
 p=i;
 }
}
if(flag==0)
 printf("\nThe %s country is not in the list...\n",srch);
else
{
 printf("The capital of %s country is %s",srch,capital[p]);
}
}







No comments:

Post a Comment