在 C 中附加字符串 [英] Appending strings in C

查看:26
本文介绍了在 C 中附加字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何组合多个字符串.例如,

How do I combine multiple strings. For example,

char item[32];
scanf("%s", item);
printf("Shopping list: %s\n", item); //I want to combine this string 
char string_2[] = "To do list: Sleep\n"; // with this string 
char hw[32];
scanf("%s", hw); 
printf("Homework: %s\n", hw); // and this string

所以他们会打印如下,

购物清单:(商品)

待办事项:睡觉

家庭作业:(hw)

但是我不想像上面的代码那样单独给printf命令,而是把字符串组合起来,最后调用printf/

But I don't want to give printf orders separately like the code above, but rather combine the strings and call printf at the end/

我将如何做到这一点,因为我无法将这样的内容保存到单独的字符串中,char string1 = ("Shopping list: %s \n", item)

How will I able to do this since I cannot save something like this into a separate string, char string1 = ("Shopping list: %s \n", item)

推荐答案

使用 strcpystrcat

char item[] = "Shopping list";
char hw[] = "To do list: Sleep \n";
char* itemhw;
itemhw = malloc(strlen(item)+strlen(hw)+1);
strcpy(itemhw, item);
strcat(itemhw, hw); 
free(itemhw);

这篇关于在 C 中附加字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆