TCS Coding Practice Question | Concatenate 2 Strings

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.");
    }
}

chevron_right



Output:

  • In C:

  • In Java:



My Personal Notes arrow_drop_up

Technical Content Engineer at GeeksForGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.