Description
Append one string to another means copy the content of one string to the end of another string.
C/C++
/* C program to append one string to another string */ //Save it as AppendTwoString.c #include<stdio.h> #include<string.h> int main(){ char str1[100], str2[100], str3[100]; printf("Enter first string : "); gets(str1); printf("Enter second string : "); gets(str2); int i=0, j=0; //Traverse first string and copy character by character into third string while(str1[i]!='\0'){ str3[j] = str1[i]; i++; j++; } i=0; //Traverse second string and copy character by character into third string while(str2[i]!='\0'){ str3[j] = str2[i]; i++; j++; } //End the third string by appending to NULL at end str3[j] = '\0'; printf("The string after append : %s",str3); //The library function strcat(str1,str2) concatenates string str2 to str1 //It is defined in string.h strcat(str1, str2); printf("\nThe string after append : %s",str1); return 0; }
Input: Enter first string : Hello Enter second string : World Output: The string after append : HelloWorld The string after append : HelloWorld
Java
/* Java program to append one string to another string */ //Save it as AppendTwoString.java import java.io.*; import java.util.Scanner; public class AppendTwoString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str1, str2; System.out.println("Enter first string : "); str1 = scanner.nextLine(); System.out.println("Enter second string : "); str2 = scanner.nextLine(); int i=0, j=0; //Need to take char array, so that character by character can be copied char str3[] = new char[str1.length()+str2.length()]; //Traverse first string and copy character by character into third string for(i=0;i<str1.length();i++) { str3[j] = str1.charAt(i); j++; } //Traverse second string and copy character by character into third string for(i=0;i<str2.length();i++) { str3[j] = str2.charAt(i); j++; } //Convert char array to string System.out.println("The string after append : " + String.valueOf(str3)); /* In java there are two built in method to concat string 1)By + (string concatenation) operator 2)By concat() method */ String newStr1 = str1 + str2; System.out.println("The string after append : " + newStr1); String newStr2 = str1.concat(str2); System.out.println("The string after append : " + newStr2); } }
Input: Enter first string : Hello Enter second string : World Output: The string after append : HelloWorld The string after append : HelloWorld The string after append : HelloWorld
Related Programs
1) Program to Compare Two Strings2) Program to Reverse a String
3) Find Substring of a Given String
4) Program to Insert a String into Another String
5) Program to check String is Palindrome
6) Program to copy string
7) Program to remove vowels from a String
8) Program to Multiply Numbers Present in a String
9) Program to remove given number from a string
10) Count Number of Words in a String