Monday, 11 December 2017

String Programs In C

To print a string

#include <stdio.h>

#include<conio.h>

void main()

{

clrscr();

 char array[50];

  printf("Enter a string\n");

    scanf("%s", array);

printf("You entered the string %s\n",array);

getch();

}

Calculate String length  


#include <stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
 clrscr();
   char a[50];
   int length;
  printf("Enter a string to calculate it's length\n");
   gets(a);
 length = strlen(a);
 printf("Length of entered string is = %d\n",length);
 getch();
}

String comparison


#include <stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char a[100], b[100];
clrscr();
  printf("Enter first string\n");
   gets(a);
 printf("Enter second string\n");
   gets(b);
  if (strcmp(a,b) == 0)
      printf("Entered strings are equal.\n");
   else
      printf("Entered strings are not equal.\n");
getch();
}

String copy

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

#include<conio.h>

void main()

{

 char source[100], destination[100];

 clrscr();

   printf("Input a string\n");

   gets(source);

 strcpy(destination, source);

 printf("Source string:%s\n", source);

   printf("Destination string:%s\n", destination);

getch();

}

C program to concatenate strings

#include <stdio.h>

#include<string.h>

#include<conio.h>

void main()

{

   char a[1000], b[1000];

   clrscr();

   printf("Enter the first string\n");

   gets(a);

 printf("Enter the second string\n");

   gets(b);

  strcat(a,b);

printf("String obtained on concatenation is %s\n",a);

getch();

}

To find substring of a String

#include <stdio.h>

#include<string.h>

#include<conio.h>

void main()

{

char string[100], sub[100];

   int position, length, c = 0;

   clrscr();

   printf("Input a string\n");

   gets(string);

   printf("Enter the position and length of substring\n");

   scanf("%d%d", &position, &length);

 

   while (c < length) {

      sub[c] = string[position+c-1];

      c++;

   }

   sub[c] = '\0';

  printf("Required substring is \"%s\"\n", sub);

getch();

}

Reverse of a String Without strrev Function

#include <stdio.h>

#include<string.h>

#include<conio.h>

void main()

{

  char str[50], temp;

   int i, j = 0;

 clrscr();

   printf("\nEnter the string :");

   gets(str);

 

   i = 0;

   j = strlen(str) - 1;

 

   while (i < j) {

      temp = str[i];

      str[i] = str[j];

      str[j] = temp;

      i++;

      j--;

   }

 printf("\nReverse string is :%s", str);

getch();

}


 

No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...