Skip to content
Related Articles

Related Articles

Improve Article

TCS Coding Practice Question | Concatenate 2 Strings

  • Last Updated : 09 Apr, 2019

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:
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :