c - C 是否有任何用于执行字符串添加的工具?

标签 c string algorithm data-structures tree

我正在制作一个函数,该函数返回表示为树状函数的导数

      /   +    \
     *          ^
   /   \      /   \
  x     5   3.14   x

具有以下形式的节点

typedef struct node
{
    char * fx; // function
    struct node * gx; // left-hand side
    char * op; // operator
    struct node * hx; // right-hand side
} node;

如果一个节点没有子节点,例如上面例子中的x, 5, 3.14,然后是它的op, gxhxNULL,否则其 fxNULL

我计算导数的函数看起来像

char * deriveFromTree ( node * rt )
{
    char * buff = malloc(100*sizeof(char));
    int curBuffIdx = 0;
    if (rt->op) // if rt is of the form rt = gx op hx
    {
        char * dgdx = deriveFromTree(rt->gx); // g'(x)
        char * dhdx = deriveFromTree(rt->hx); // h'(x)
        char thisop = *rt->op;
        if (thisop == '+' || thisop == '-')
        {
            // ... want to do equivalent of
            //     buff = dgdx + thisop + dhdx
        }
        else if (thisop == '*')
        {
            // ...
        }
        else if (thisop == '/')
        {
            // ...
        }
        else if (thisop == '^')
        {
            // ...
        }
    }
    else // rt is a base expression -- x or a constant
    {
        buff[curBuffIdx] = strcmp(rt->fx, 'x') ? '1': '0';
    }
    buff[++curBuffIdx] = '\0';
    return buff;
}

但是我在所有的字符串添加上都被绊倒了。如果已经有一种紧凑的方法,我可以从头开始创建一个字符串加法器

            // ... want to do equivalent of
            //     buff = dgdx + thisop + dhdx

然后我想使用那个工具。

最佳答案

如果您的 C 标准库是 GNU 或 *BSD,那么您可能有 asprintf 可用。不过,您可能需要启用功能测试宏才能使用它。如果您没有可用的 asprintf,可以根据 C 标准 vsnprintf 函数轻松定义它。

asprintf 将格式的结果作为新分配的字符串返回(您有责任释放)。所以你可以写,例如:

char* buff;
int n = asprintf(&buff, "%s%c%s", dgdx, thisop, dhdx);

我通常使用包装函数,它返回字符串而不是长度,所以你可以这样写:

char* buff = concatf("%s%c%s", dgdx, thisop, dhdx);

这里是三个简单的实现;第一个将在带有 vasprintf 的系统上工作;第二个在具有 Posix vsnprintf 的系统上;第三个用于 Windows,它显然实现了不同的 snprintf 接口(interface)。

// Version 1, systems which have vasprintf:
char* concatf(const char* fmt, ...) {
  va_list args;
  char* buf = NULL;
  va_start(args, fmt);
  int n = vasprintf(&buf, fmt, args);
  va_end(args);
  if (n < 0) { free(buf); buf = NULL; }
  return buf;
}

// Version 2: Systems without vasprintf but with vsnprintf
char* concatf(const char* fmt, ...) {
  va_list args;
  va_start(args, fmt);
  char* buf = NULL;
  int n = vsnprintf(NULL, 0, fmt, args);
  va_end(args);
  if (n >= 0) {
    va_start(args, fmt);
    buf = malloc(n+1);
    if (buf) vsnprintf(buf, n+1, fmt, args);
    va_end(args);
  }
  return buf;
}

// Version 3: Windows
// Apparently, the implementation of vsnprintf on Windows returns -1
// if not enough space has been provided. So here is the above code
// rewritten according to the documentation I found in
//  https://msdn.microsoft.com/en-us/library/w05tbk72%28VS.71%29.aspx
// and
//  https://msdn.microsoft.com/en-us/library/1kt27hek%28v=vs.71%29.aspx
// but totally untested. (If you try it, let me know)
char* concatf(const char* fmt, ...) {
  char* buf = NULL;
  va_list args;
  va_start(args, fmt);
  int n = _vscprintf(fmt, args);
  va_end(args);
  if (n >= 0) {
    va_start(args, fmt);
    buf = malloc(n+1);
    if (buf) _vsnprintf(buf, n+1, fmt, args);
    va_end(args);
  }
  return buf;
}

这是我所知道的与其他语言中的字符串连接运算符最简洁的等价物。 (它不一定是执行时间最高效的,但它可能是程序员时间。)

关于c - C 是否有任何用于执行字符串添加的工具?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30685109/

相关文章:

python - 连接两个列表中相同索引处的字符串

java - 检查空的 JFormattedTextField

algorithm - 极小极大算法的伪代码

c - 如何替换 ncurses & C 中的字符串菜单项

c - 如何获取十六进制数的位 AES 实现

c - 结构分隔变量

c# - 如何测量在 MacBook 上运行的 VirtualBox 上开发的 C# 算法的性能?

在 C 中使用链表创建稀疏矩阵

java - 使用递增计数命名多个字符串

algorithm - 半局部编辑距离