Here, we have a basic program example to copy one string into another string using different languages. This program is created in c language, c++, Java, and Python.
Code to copy string in C language
#include <string.h>
#include <stdlib.h>
void main()
{
char str1[100], str2[100];
int i;
printf("Input the string : ");
fgets(str1, sizeof str1, stdin);
i=0;
while(str1[i]!='\0')
{
str2[i] = str1[i];
i++;
}
str2[i] = '\0';
printf("\nThe First string is : %s\n", str1);
printf("The Second string is : %s\n", str2);
printf("Number of characters copied : %d\n\n", i);
}
Code to copy string in C++ language
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
char str1[100], str2[100];
int i;
cout<<"Enter the string: ";
cin>>str1;
i=0;
while(str1[i]!='\0')
{
str2[i] = str1[i];
i++;
}
str2[i] = '\0';
cout<<"\nThe First string is : "<<str1;
cout<<"\nThe Second string is : "<<str2<<endl;
cout<<"Number of characters copied : "<<i;
cout<<endl;
return 0;
}
Code to copy string in Python language
str1 = input("Please Enter the String : ")
str2 = ''
for i in str1:
str2 = str2 + i
print("The First string is : ", str1)
print("The Second string is : ", str2)
Code to copy string in Java language
import java.util.*;
public class copyString
{
public static void main(String args[])
{
String str1;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String : ");
str1 = scan.nextLine();
StringBuffer str2 = new StringBuffer(str1);
System.out.print("The First string is : " +str1 + "\n");
System.out.print("The Second string is : " +str2 + "\n");
}
}