Open In App

TCS Coding Practice Question | Concatenate 2 Strings

Improve
Improve
Like Article
Like
Save
Share
Report

Given two Strings, the task is to concatenate the two Strings using Command Line Arguments.

Examples:

Input: str1 = "hello", str2 = "world"
Output: helloworld

Input: str1 = "Geeks", str2 = "World"
Output: GeeksWorld

Approach:

  • Since the Strings are entered as Command line Arguments, there is no need for a dedicated input line
  • Extract the input Strings from the command line argument
  • Concatenate the given strings using the respective methods.
  • Print or return the concatenated strings

Program:

C




// C program to concatenate the two Strings
// using command line arguments
  
#include <stdio.h>
#include <stdlib.h> /* atoi */
#include <string.h>
  
// Function to concatenate the Strings
char* concat(char dest[], char src[])
{
  
    // Appends the entire string
    // of src to dest
    strcat(dest, src);
  
    // Return the concatenated String
    return dest;
}
  
// Driver code
int main(int argc, char* argv[])
{
    // Check if the length of args array is 1
    if (argc == 1)
        printf("No command line arguments found.\n");
    else {
  
        // Get the command line arguments
        // and concatenate them
        printf("%s\n", concat(argv[1], argv[2]));
    }
    return 0;
}


Java




// Java program to concatenate the two Strings
// using command line arguments
  
class GFG {
  
    // Function to concatenate the String
    public static String concat(String dest, String src)
    {
  
        // Return the concatenated String
        return (dest + src);
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Check if length of args array is
        // greater than 0
        if (args.length > 0) {
  
            // Get the command line arguments
            // and concatenate them
            System.out.println(concat(args[0], args[1]));
        }
        else
            System.out.println("No command line "
                               + "arguments found.");
    }
}


Output:

  • In C:

  • In Java:



Last Updated : 11 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads