将整数粘贴到字符串和字符*
如何将整型变量添加到字符串和 char* 变量中?例如:
int a = 5;
字符串 St1 = "书", St2;
char *Ch1 =“注释”,Ch2;
St2 = St1 + a -->第五册
Ch2 = Ch1 + a -->注5
谢谢
How can I add an integer variable to a string and char* variable? for example:
int a = 5;
string St1 = "Book", St2;
char *Ch1 = "Note", Ch2;
St2 = St1 + a --> Book5
Ch2 = Ch1 + a --> Note5
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C++ 执行此操作的方法是:
您也可以使用
Ch1
执行相同的操作:The C++ way of doing this is:
You can also do the same thing with
Ch1
:例如,对于 char* ,您需要创建另一个足够长的变量。您可以“修复”输出字符串的长度,以消除超出字符串末尾的可能性。如果这样做,请小心使其足够大以容纳整个数字,否则您可能会发现 book+50 和 book+502 都显示为 book+50 (截断)。
以下是如何手动计算所需的内存量。这是最有效但容易出错的方法。
ch2 现在包含组合文本。
或者,稍微不那么棘手,也更漂亮(但效率较低),您还可以对 printf 进行“试运行”以获得所需的长度:
如果您的平台包含 asprintf,那么这会容易得多,因为 asprintf 会自动分配正确的长度新字符串的内存量。
ch2 现在包含组合文本。
c++ 没有那么繁琐,但我将把它留给其他人来描述。
for
char*
you need to create another variable that is long enough for both, for instance. You can 'fix' the length of the output string to remove the chance of overrunning the end of the string. If you do that, be careful to make this large enough to hold the whole number, otherwise you might find that book+50 and book+502 both come out as book+50 (truncation).Here's how to manually calculate the amount of memory required. This is most efficient but error-prone.
ch2 now contains the combined text.
Alternatively, and slightly less tricky and also prettier (but less efficient) you can also do a 'trial run' of printf to get the required length:
if your platform includes asprintf, then this is a lot easier, since asprintf automatically allocates the correct amount of memory for your new string.
ch2 now contains the combined text.
c++ is much less fiddly, but I'll leave that to others to describe.
您需要创建另一个足够大的字符串来容纳原始字符串,后跟数字(即将与数字的每个数字对应的字符附加到这个新字符串)。
You need to create another string large enough to hold the original string followed by the number (i.e. append the character corresponding to each digit of the number to this new string).