如何使用c合并两个字符串?

时间:2017-06-04 10:50:18

标签: c arrays string string-concatenation

#include<stdio.h>

/* a function to merge two strings */

void stringMerge(char* f, char* s){

while(*f++);

while((*f++ = *s++));

}

int main(){

char s1[] = "Hello ";

char s2[] = "World";

stringMerge(s1,s2);

printf("%s",s1);

return 0;

}

2 个答案:

答案 0 :(得分:0)

考虑到要连接的字符串的声明,那么它似乎意味着以下函数实现。

library(Matrix)
n <- 3
P <- array(1:12, dim = c(2, 2, n))
P <- matrix(P, nrow = 2)
A <- matrix(0.25, nrow = 2, ncol = n)
R <- matrix(-1, nrow = 2, ncol = n) 
v <- rep(0.1, 2)
v <- bdiag(rep(list(v),n))
v <- rowSums(A * (R + (P %*% v)))
## [1] 0.15 0.30

或以下

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char * stringMerge(const char *s1, const char *s2)
{
    size_t n = strlen(s1);

    char *p = (char *)malloc(n + strlen(s2) + 1);

    if (p)
    {
        strcpy(p, s1);
        strcpy(p + n, s2);
    }

    return p;
}


int main( void )
{
    char s1[] = "Hello ";
    char s2[] = "World";

    char *p = stringMerge(s1, s2);

    puts(p);

    free(p);
}

在两个程序中输出都是

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char * stringMerge(const char *s1, const char *s2)
{
    size_t n = strlen(s1);

    char *p = (char *)malloc(n + strlen(s2) + 1);

    if (p)
    {
        char *t = p;
        while (*t = *s1++) ++t;
        do { *t = *s2++; } while (*t++);
    }

    return p;
}

int main( void )
{
    char s1[] = "Hello ";
    char s2[] = "World";

    char *p = stringMerge(s1, s2);

    puts(p);

    free(p);
}

答案 1 :(得分:-2)

我建议您使用strncat()中的string.h。这是你的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
    char *s1 = "Hello ";
    char *s2 = "World\n";
    size_t s1_size = strlen(s1);
    size_t s2_size = strlen(s2);
    char *concat = calloc((s1_size + 1 + s2_size + 1), sizeof(char));
    if (concat == NULL) {
        perror("Calloc");
        exit(EXIT_FAILURE);
    }
    strncat(concat, s1, s1_size);
    strncat(concat, s2, s2_size);
    printf("%s", concat);
    free(concat);
    return 0;

}