简体   繁体   English

使用 strcat 在单个字符串中复制 n 个单词

[英]Copy n words in a single string using strcat

How can i copy n different words in a single string using strcat?如何使用 strcat 在单个字符串中复制 n 个不同的单词? This is my code but doesn't work.这是我的代码,但不起作用。 The size of the single words is 40. arr contain the different words and fin is my final string.单个单词的大小为 40。 arr包含不同的单词, fin是我的最终字符串。

char *cat(char **arr,int n){
    int i;
    char *fin;
    fin = malloc(n*40);
    for(i=0;i<n;i++){
        strcat(arr[i],fin);
    }
    return fin;
}

to concatenate the strings from arr info fin you need to reverse the order of argument, so replace要连接来自arr info fin的字符串,您需要颠倒参数的顺序,所以替换

strcat(arr[i],fin);

by经过

strcat(fin, arr[i]);

because the first argument is the destination and the second the source.因为第一个参数是目标,第二个是源。

But that suppose to initialize fin to be an empty string, so before the loop do但是假设将fin初始化为空字符串,所以在循环之前

*fin = 0;

The size of the single words is 40单字大小为40

warning if you speak about the length rather than the size including the terminating null character you need to allocate one more:如果您谈论长度而不是大小,包括终止 null 字符,则警告您需要再分配一个:

fin = malloc(n*40 + 1);

From your remark:从你的评论中:

Moreover it is all joined without space how can i add them between each word?此外,它都是无空格连接的,我如何在每个单词之间添加它们?

if you want to add a space you need to allocate more and to explicitly add your space, can be:如果要添加空间,则需要分配更多空间并显式添加空间,可以是:

fin = malloc(n*41+1);
*fin = 0;
for(i=0;i<n;i++){
    strcat(fin, arr[i]);
    strcat(fin, " ");
}

note if n large strcat search the end of fin which is more and more long, better to save the pointer to the end and use strcpy , for instance:请注意,如果n large strcat搜索越来越长的fin的末尾,最好将指针保存到末尾并使用strcpy ,例如:

char * fin = malloc(n*41+1);

if (n == 0) {
  *fin = 0;
}
else {
  char * p = fin;

  for(i=0;i<n;i++){
    strcpy(p, arr[i]);
    p += strlen(p) + 1;
    p[-1]  = ' ';
  }
  p[-1]  = 0;
}
return fin;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM