All articles
c

A program to explain string manipulations - Part 1

Share this article

Share on LinkedIn Share on X (formerly Twitter)

C Programming Language 071

  • Write a program to find

    1. length of a string
    2. copy one string to another
    3. concatenate two strings
    4. compare two strings
  • With string handling functions

    1. strlen()
    2. strcpy()
    3. strcat()
    4. strcmp()

Program

#include <stdio.h>
#include <string.h>
 
void main()
{
    char str1[30], str2[30], str3[30];
    int i;
 
    printf("Enter string: ");
    gets(str1);
 
    printf("Length of string = %ld\n", strlen(str1));
 
    strcpy(str2, str1);
    printf("After copying...\n");
    printf("str1 = %s \nstr2 = %s \n", str1, str2);
 
    printf("Enter another string: ");
    gets(str3);
 
    if (strcmp(str1, str3) == 0)
    {
        printf("Strings are equal\n");
    }
    else
    {
        printf("Strings are not equal\n");
    }
 
    strcat(str1, str3);
    printf("After concatenation...\n");
    printf("str1 = %s \n", str1);
 
    printf("\n");
}

Result

Enter string: hello
Length of string = 5
After copying...
str1 = hello
str2 = hello
Enter another string: world
Strings are not equal
After concatenation...
str1 = helloworld

Comments