2 つの文字列を連結したときの大きさだけを判断する必要がある場合は、2 つの文字列snprintf
の合計の長さを判断するための最小限の操作が 2 つのstrlen
呼び出しで行われるため、 を優先する特別な理由はありません。snprintf
文字をカウントする2つの文字列をたどるだけでなく、パラメーターをチェックしてフォーマット文字列を解析する必要があるため、ほぼ確実に遅くなります。
...しかし...snprintf
2 つの文字列を連結し、通常のケースを処理するには大きすぎない静的なバッファーを使用するシナリオで使用するのは賢明な方法かもしれ大きな文字列の場合に割り当てられたバッファ。例:
/* static buffer "big enough" for most cases */
char buffer[256];
/* pointer used in the part where work on the string is actually done */
char * outputStr=buffer;
/* try to concatenate, get the length of the resulting string */
int length = snprintf(buffer, sizeof(buffer), "%s%s", str1, str2);
if(length<0)
{
/* error, panic and death */
}
else if(length>sizeof(buffer)-1)
{
/* buffer wasn't enough, allocate dynamically */
outputStr=malloc(length+1);
if(outputStr==NULL)
{
/* allocation error, death and panic */
}
if(snprintf(outputStr, length, "%s%s", str1, str2)<0)
{
/* error, the world is doomed */
}
}
/* here do whatever you want with outputStr */
if(outputStr!=buffer)
free(outputStr);