在C中编写简洁的代码

时间:2018-03-31 00:36:12

标签: c strcat

strcat(msg, ": ");
strcat(msg, buf);

有没有办法在一行中执行此操作?我想让我的代码更清洁,减少混乱

3 个答案:

答案 0 :(得分:1)

尝试创建格式化字符串,而不是进行多个连接。尝试这样的事情:

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

int main()
{
    char *before_colon = "Text before colon";
    char *after_colon = "Text after colon";

    // Make a string that is the size of both formatted strings, plus a
    // character for the space, colon, and null character.
    char final_string[strlen(before_colon) + strlen(after_colon) + 3];

    // This works just like any other C formatted function (i.e printf, scanf)
    sprintf(final_string, "%s: %s", before_colon, after_colon);
    printf("%s\n", final_string);
}

输出:

Text before colon: Text after colon

答案 1 :(得分:0)

这是Charlie Sale的修改代码,它有自己的函数来计算字符串中的字符。因此,在数组声明中调用StrLen。

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

int StrLen(char* PtrFirstChar)
{
    int n = 0;
    while(*(PtrFirstChar++)) // will evaluate to FALSE when '\0' reached
        n++;
    return n;
}

int main()
{
char *before_colon = "Text before colon";
char *after_colon = "Text after colon";

// Make a string that is the size of both formatted strings, plus a
// character for the space, colon, and null character.
char final_string[StrLen(before_colon) + StrLen(after_colon) + 3];

// This works just like any other C formatted function (i.e printf, scanf)
sprintf(final_string, "%s: %s", before_colon, after_colon);
printf("%s\n", final_string);
}

答案 2 :(得分:0)

您可以编写自己的strcat变体!

我将使用strncat作为基础,因为strcat是一个非常糟糕的主意:

#include <stddef.h> /* for size_t */
#include <stdarg.h> /* for va_* */

char *
mstrncat(char *d, size_t maxlen, ...)
{
    va_list ap;
    va_start(ap, maxlen);
    char *ret = d;
    /* Fast-forward */
    for (; *d && maxlen; ++d, --maxlen);
    /* Reserve a space for the terminator */
    if (maxlen)
        --maxlen;
    const char *p;
    /* Concatenate parameters one by one */
    while (maxlen && (p = va_arg(ap, const char *))) {
        while (*p && maxlen--)
            *d++ = *p++;
    }
    /* Terminate the string */
    *d = 0;
    va_end(ap);
    return ret;
}

你可以像这样使用它:

#include <stdio.h>

int
main()
{
    char test[128]="test";
    mstrncat(test, sizeof(test), "1", "two", "3", NULL);
    puts(test);
    return 0;
}