本文介绍了strcat()用于格式化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在程序中逐步构建一个字符串,当我在末尾添加一个简单字符串时,我目前正在使用strcat()的混合,但是当我添加格式化字符串时,我正在使用sprintf( ),例如:

I'm building a string piece by piece in my program and am currently using a mix of strcat() when I'm adding a simple string onto the end, but when im adding a formatted string I'm using sprintf() e.g.:

int one = 1;
sprintf(instruction + strlen(instruction), " number %d", one);

是否可以使用strcat()连接格式化的字符串,或者首选的方法是什么? / p>

is it possible to concatenate formatted string using strcat() or what is the preferred method for this?

推荐答案

您的解决方案将起作用。调用strlen有点尴尬(尤其是在字符串变得很长的情况下)。 sprintf()将返回您已使用的长度[strcat不会],因此您可以做的一件事是这样的:

Your solution will work. Calling strlen is a bit awkward (particularly if the string gets quite long). sprintf() will return the length you have used [strcat won't], so one thing you can do is something like this:

 char str[MAX_SIZE];
 char *target = str;

 target += sprintf(target, "%s", str_value);
 target += sprintf(target, "somestuff %d", number);
 if (something)
 {
    target += sprintf(target, "%s", str_value2);
 }
 else
 {
    target += sprintf(target, "%08x", num2);
 }

我不确定strcat是否比sprintf()效率更高?以这种方式使用。

I'm not sure strcat is much more efficient than sprintf() is when used in this way.

编辑:应该写一些较小的示例...

should write smaller examples...

这篇关于strcat()用于格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 19:35