String Handling functions in C++

String Handling functions in C++

Posted on Updated on

String Handling functions in C++

Example of strlen()

#include <stdio.h>

#include <string.h>

void main(){

char a[20]=”Program”;

char b[20]={‘P’,’r’,’o’,’g’,’r’,’a’,’m’,”};

char c[20];

printf(“Enter string: “);

gets(c);

printf(“Length of string a=%d \n”,strlen(a));

//calculates the length of string before null charcter.

printf(“Length of string b=%d \n”,strlen(b));

printf(“Length of string c=%d \n”,strlen(c));

}

Output

Enter string: String

Length of string a=7

Length of string b=7

Length of string c=6

Example of strcpy()
#include <stdio.h>
#include <string.h>
void main(){
    char a[10],b[10];
    printf("Enter string: ");
    gets(a);
    strcpy(b,a);   //Content of string a is copied to string b.
    printf("Copied string: ");
    puts(b);
}

Output

Enter string: Programming Tutorial
Copied string: Programming Tutorial
Example of strcat()
#include <stdio.h>
#include <string.h>
Void main(){
    char str1[]="This is ", str2[]="programiz.com";
    strcat(str1,str2);   //concatenates str1 and str2 and resultant string is stored in str1.
    puts(str1);    
    puts(str2); 
}

Output

This is programiz.com
programiz.com
Example of strcmp()
#include <stdio.h>
#include <string.h>
int main(){
  char str1[30],str2[30];
  printf("Enter first string: ");
  gets(str1);
  printf("Enter second string: ");
  gets(str2);
  if(strcmp(str1,str2)==0)
      printf("Both strings are equal");
  else
      printf("Strings are unequal");
  return 0;
}

Output

Enter first string: Apple     
Enter second string: Apple
Both strings are equal.

Posted By-: Vissicomp Technology Pvt. Ltd.

Website -: http://www.vissicomp.com

Advertisements