【问题标题】:padding string by adding char to the string通过向字符串添加 char 来填充字符串
【发布时间】:2021-11-12 18:23:21
【问题描述】:

我正在尝试创建一个向字符串添加下划线的填充函数。字符串长度应为 16,如果字符串小于 16,则函数应添加下划线,直到字符串长度为 16,然后返回填充字符串。如果字符串超过 16 个,填充函数应该忽略字符并返回字符串的前 16 个字符。

char* padding(char* plaintext) {
    char ch = '_';
    size_t len = strlen(plaintext);
    size_t lench = 17 - len;
    char *p_text = malloc(len + 1 + 1);
    strcpy(p_text, plaintext);
    
    if (len < 17) {
        int i;
           
        for (i = lench; i < 16; i++) {
            p_text[i] = ch;
        }
    }
        
    // p_text[17] = '\0';
    return p_text;
}
     
int main() {
    char *key = "0123456789ABCDEF"; 
       
    while (1) {
        char plaintext[WIDTH + 1];
            
        printf("Enter a string: ");
        fgets(plaintext, WIDTH + 1, stdin);
           
        if (plaintext[0] == '\n' || plaintext[0] == '\r') 
            break;
            
        char* padded_plaintext = padding(plaintext);
        printf("padded plaintext = %s\n", padded_plaintext);
          
        printf("\n");
            
    }
    
    return 0;
}

这段代码返回了一个奇怪的结果。

【问题讨论】:

  • 您为p_text 分配的空间不应依赖于输入。它应该始终是 17。
  • while(1) 循环中有内存泄漏很好地证明了为什么这是一个糟糕的 api。您可能应该让调用者传入一个缓冲区,其中将写入填充字符串,而不是mallocing 空间。如果您使用malloc,请确保您使用free

标签: c string padding


【解决方案1】:

考虑一个干净的解决方案来解决这个问题。希望看到这一点(以及随附的解释)有所帮助。

char *padded_string(char *src, int width, char ch) {
    char *dest = calloc(1, width + 1);

    strncpy(dest, src, width);

    for (int i = 0; i < width; i++) {
        if (!dest[i]) {
            dest[i] = ch;
        }
    }

    return dest;
}

我们通过使用calloc 分配width + 1 字节来为自己提供一个干净的工作状态。使用calloc 将确保所有字节都设置为0。在 C 中处理字符串时,它们需要以 null 结尾,所以这非常有用。

我们将src 的内容复制到dest。使用strncpy 可以确保如果源字符串比我们想要结束的字符串长,我们不会出现缓冲区溢出。

接下来我们从0width 次循环。如果i 处的目标字符串中的字符是'\0',我们将在该索引处插入填充字符。

现在,因为我们使用了calloc,并且我们分配了一个超出所需字符长度的额外字节,所以字符串已经以空值结尾,我们可以简单地返回它的指针。

【讨论】:

    【解决方案2】:

    您为 p_text 分配的空间不应取决于输入。它应该始终为 17。如果 len + 1 + 1 p_text[i] 将导致您正在使用的 i 的某些值出现未定义的行为。你应该替换:

    char *p_text = malloc(len + 1 + 1);
    

    char *p_text = malloc(17);
    

    并在写入之前检查p_text 不为NULL。

    另外,注释掉的//p_text[17] = '\0'; 是错误的。那应该是

    p_text[16] = '\0';
    

    【讨论】:

      猜你喜欢
      • 2011-03-08
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 2021-03-09
      • 2014-10-18
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多