简体   繁体   English

在C中建立字串

[英]Building a string in C

This seems like a question that would have been asked before, but I couldn't find it. 这似乎是一个以前曾被问过的问题,但我找不到。 (If you do, please point me there and close this as a duplicate.) (如果这样做,请把我指向那里,并关闭它作为副本。)

I have C code which works something like this: 我有C代码,其工作原理如下:

printf("some characters");
for (; n >= 0; n--)
{
    printf(", %s", f(n, k));
}
printf("more characters");

for some variables n and k and function char* f(int n, int k) which are not important here. 对于某些变量nk以及函数char* f(int n, int k)在这里并不重要。 ( n and k are not constant.) I would like to convert the code above to a function which returns a char* rather than simply using printf to display it. nk不是常数。)我想将上面的代码转换为一个返回char*的函数,而不是简单地使用printf来显示它。 (It will ultimately be printed but this lets me do some refactoring and is of course easier to test that way.) Of course I could just create the strings and copy them over character-by-character but surely there is a better (cleaner, faster, more idiomatic) way of doing this. (它将最终被打印出来,但这使我可以进行一些重构,并且当然可以更容易地进行测试。)当然,我可以创建字符串并逐个字符地复制它们,但是肯定有更好的选择(更干净,更快,更惯用的方式)。

In my particular application f is a very simple function, sort of a relative of itos , but which is not cacheable in any meaningful way due to k . 在我的特定应用程序中, f是一个非常简单的函数,有点像itos的相对itos ,但是由于k ,它不能以任何有意义的方式进行缓存。 But I welcome ideas which are good for that case as it may be useful to others in the future. 但是,我欢迎对这种情况有用的想法,因为它将来可能对其他人有用。

Step 1 would be to allocate a big enough buffer for the string. 步骤1是为字符串分配足够大的缓冲区。 Then use sprintf to print into the buffer. 然后使用sprintf打印到缓冲区中。 The standard idiom is 标准成语是

int index = sprintf( buffer, "some characters" );
for (; n >= 0; n--)
{
    index += sprintf( &buffer[index], ", %s", f(n, k) );
}
index += sprintf( &buffer[index], "more characters" );

The sprintf function returns the length of the string that it wrote, which allows you to keep track of where you are in the buffer. sprintf函数返回它写入的字符串的长度,这使您可以跟踪缓冲区中的位置。


You could also have the caller pass a buffer and size. 您还可以让调用方传递缓冲区和大小。 In that case, it's best to use snprintf to avoid overrunning the buffer. 在这种情况下,最好使用snprintf以避免溢出缓冲区。 So the function would look something like this 所以功能看起来像这样

char *create_string( char *buffer, int size, int n, int k )
{
    ...
    index += snprintf( &buffer[index], size-index, ", %s", f(n, k) );
    ...
    return buffer;
}

where the size parameter is the size of the buffer . 其中size参数是buffer的大小。

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

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