C Online Compiler
Example: String Concatenation in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// String Concatenation #include <stdio.h> #include <string.h> // Required for strcat() int main() { // Step 1: Declare destination and source strings char destination[50] = "Hello"; // Must be large enough for combined string char source[] = ", World!"; // Step 2: Print initial destination string printf("Initial Destination: \"%s\"\n", destination); // Step 3: Use strcat() to append source to destination strcat(destination, source); // Step 4: Print the concatenated string printf("Concatenated String: \"%s\"\n", destination); // Example with strncat for safety char sentence[50] = "This is a "; char fragment[] = "short sentence that is still quite long."; printf("\nSafe Concatenation Example:\n"); printf("Initial sentence: \"%s\"\n", sentence); // Calculate remaining space: sizeof(sentence) - strlen(sentence) - 1 // -1 for the null terminator that strncat will add strncat(sentence, fragment, sizeof(sentence) - strlen(sentence) - 1); printf("Concatenated sentence: \"%s\"\n", sentence); return 0; }
Output
Clear
ADVERTISEMENTS