如何用C另一个字符串插入一个字符串 [英] How to insert a string in another string in C
本文介绍了如何用C另一个字符串插入一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在一个特定位置中插入另一个字符串的字符串。这里有一个简单的例子:
I need to insert a string in another string at a specific place. Here's a simple example:
char *a = "Dany S.";
char *b = "My name is *a , I come from ... ";
所以,在的* A
我希望有达尼字符串
B
秒。
So, in string b
in place of *a
I expect to have Dany S.
该怎么做?
推荐答案
最好/最简单的方法是使用标准C约定:
The best/easiest way would be to use standard C conventions:
char *a = "Dany S.";
char *b = "My name is %s, I come from...";
char *c = malloc(strlen(a) + strlen(b));
sprintf( c, b, a );
然后 C
包含新的字符串。当你使用做ç
,你需要释放内存:
Then c
contains your new string. When you're done with c
, you will need to free the memory:
free( c );
如果您要在终止该行,那么你可以声明输出使用 C
B
为:
If you want to use c
in an output that terminates the line, then you can declare b
as:
char *b = "My name is %s, I come from...\n";
这篇关于如何用C另一个字符串插入一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文