【问题标题】:Generate a string of arbitrary size appending other strings: how?生成任意大小的字符串附加其他字符串:如何?
【发布时间】:2018-06-23 10:14:59
【问题描述】:

我在动态构造未知大小的字符串时遇到了一些问题。为了解释我的问题,我编写了这个小代码(伪 C 代码),它应该每次生成一个 finalstring 附加一个新字符串:

char *finalstring;
while (/* condition */) {
    char *tmp = get_new_string();
    finalstring = strcat(finalstring, tmp);
}
printf("%s\n", finalstring);

在每次迭代中,get_new_string() 都会得到一个不同的字符串,我想将它加到finalstring。每个字符串将始终是一个固定的STRSIZE,因此在每次迭代中finalstring 可以增长STRSIZEchars。

我怎样才能真正在 C 中实现它?我不确定我应该如何使用mallocs...

【问题讨论】:

    标签: c string append


    【解决方案1】:

    您可以reallocate(使用realloc)到oldsize + new string length 来获取可以连接新字符串的变量。这将为您解决问题。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main (void) {
        char *finalstring = NULL;
        size_t oldsize = 0;
        size_t i=0;
        char s[][10]={"AA","BB","CC","DD"};
        size_t sz = sizeof s / sizeof s[0];
        while (i < sz) {
            size_t newsize = strlen(s[i]);
            size_t templen = newsize + oldsize ;
            if(oldsize == 0) templen++;
            char *temp  = realloc(finalstring , templen );
            if(temp == NULL){
                perror("realloc failed");
                exit(EXIT_FAILURE);
            }
            finalstring = temp;
    
            if(oldsize == 0){
                strcpy(finalstring,s[i]);
            }
            else
                strcat(finalstring,s[i]);
            oldsize = z;
            i++;
        }
    
       printf("%s\n",finalstring );
       free(finalstring);
       return 0;
    }
    

    对于第一个字符串,分配了更多空间来保存\0。连续的字符串不需要,因为以前的\0 将被覆盖。您将使用从get_new_string() 函数返回的字符串,而不是s[i]

    【讨论】:

      【解决方案2】:

      生成任意大小的字符串附加其他字符串:如何?

      跟踪字符串长度并根据需要为新字符串重新分配。

      char *final_string = NULL;
      size_t final_len = 0;  // size_t is the best type for "size" math and array indexing
      while (/* condition */) {
          char *tmp = get_new_string();
          size_t tmp_len = strlen(tmp);
      
          // Allocate enough for the length of both parts and a \0   
          char *s = realloc(final_string, final_len + tmp_len + 1);
          if (s == NULL) {
            exit(EXIT_FAILURE);
          }
          final_string = s; 
      
          // As code knows the strings lengths, 
          // easy enough to use fast memcpy to concatenate....
          memcpy(final_string + final_len, tmp, tmp_len + 1);
          final_len += tmp_len;
      }
      
      if (final_string) {  // If needed in case loop body never executed.
        printf("%s\n", final_string);
      }
      free(final_string);
      

      这个答案没有利用“每个字符串将始终是一个固定的STRSIZE”。这是一个微不足道的条件。

      【讨论】:

        猜你喜欢
        • 2015-07-14
        • 2015-03-17
        • 2023-03-22
        • 2012-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-30
        • 2021-01-29
        相关资源
        最近更新 更多