Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,913 questions

51,845 answers

573 users

How to concatenate two strings in C

3 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char* concat(const char *s1, const char *s2);
  
int main(void)
{
    char s1[] = "c c++ c#";
    char s2[] = " java python";
 
    char* s = concat(s1, s2);
     
    puts(s);
     
    free(s);
  
    return 0;
}

char* concat(const char *s1, const char *s2) {
    char *result = (char *)malloc(strlen(s1) + strlen(s2) + 1);
     
    strcpy(result, s1);
    strcat(result, s2);
 
    return result;
}
  
  
   
/*
run:
     
c c++ c# java python
  
*/

 



answered Jun 13, 2017 by avibootz
edited Mar 30, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char* concat(const char *s1, const char *s2);
  
int main(void)
{
    char s1[] = "c c++ c#";
    char s2[] = " java python";
 
    char* s = concat(s1, s2);
     
    puts(s);
     
    free(s);
  
    return 0;
}

char* concat(const char *s1, const char *s2) {
    char *result = (char *)malloc(strlen(s1) + strlen(s2) + 1);
     
    sprintf(result, "%s %s", s1, s2);
 
    return result;
}
  
  
   
/*
run:
     
c c++ c# java python
  
*/

 



answered Mar 30, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char* concat(const char *s1, const char *s2);
  
int main(void)
{
    char s1[] = "c c++ c#";
    char s2[] = " java python";
 
    char* s = concat(s1, s2);
     
    puts(s);
     
    free(s);
  
    return 0;
}

char* concat(const char *s1, const char *s2) {
    size_t len1 = strlen(s1);
    size_t len2 = strlen(s2);
    
    char *result = (char *)malloc(len1 + len2 + 1);
     
    memcpy(result, s1, len1);
    result[len1] = ' ';
    memcpy(result + len1 + 1, s2, len2 + 1); // len2 + (1 -> for null)
 
    return result;
}
  
  
   
/*
run:
     
c c++ c# java python
  
*/

 



answered Mar 30, 2024 by avibootz

Related questions

1 answer 142 views
1 answer 126 views
126 views asked Jan 5, 2021 by avibootz
2 answers 172 views
1 answer 128 views
4 answers 301 views
301 views asked May 10, 2021 by avibootz
1 answer 152 views
1 answer 142 views
...