问题描述
这可能很简单,当你从未做过指针并习惯于使用Delphi或Visual Basic中的
luxery字符串时,C可以尽管如此。我想要做的就是将字符串添加到字符串中。我看了一下string.h文件,但是
我没有找到那种功能(那个字符串库超过7年b
岁)所以我决定把这个功能写在自己身上。它似乎工作
虽然当我试图在这些动作之间做printf时我很奇怪
消息。无论如何,现在我正在尝试将字符添加到2个字符串。第一个字符串
是可以的,但第二个字符串似乎已经被淹没了。这是我的代码:
/ *将1个字符添加到字符串中的函数* /
char * strAddChar(char * s1,char c){
char * s;
s = s1;
s = s + strlen(s1); //写的位置
* s = c; //这应该在null char
的地方首先
//是。
s ++;
* s = 0; //添加一个新的空字符串
return(s1);
} // strAddChar
/ *这就是我使用函数* /
main(){
char * res1 ="" ;; //空字符串1
char * res2 ="" ;; //空字符串2
strAddChar(res1,'a'');
strAddChar(res1,''b'');
strAddChar(res1,''c'');
strAddChar(res2,''1'');
strAddChar(res2,''''');
strAddChar(res2,''3'');
printf("%s \ n",res1); // test
printf("%s \ n",res2);
好的,输出应为res1 =" abc"和res2 =123但这是我的结果:
res1 =" abc" res2 =" bc123"
" bc"进入res2 ??如何修复这个功能?
问候,
瑞克
Hi,
This is probably simple byt when you never did pointers and being used to
luxery strings like in Delphi or Visual Basic, C can get though. What I''m
trying to do is to add chars to a string. I looked in the string.h file but
I didn''t find that kind of function (that string library is more than 7
years old) so I decided to write that function on myself. It seems to work
although when I''m trying to do printf''s between those actions I get strange
messages. Anyway, now I''m trying to add chars to 2 strings. The first string
is ok but the second one seems to get overwrited. Here''s my code :
/* the function to add 1 char to a string */
char *strAddChar(char *s1, char c){
char *s;
s = s1;
s = s + strlen(s1); // the position to write
*s = c; // this should be on the place where the null char
first
// was.
s++;
*s = 0; // add a new null string
return(s1);
} // strAddChar
/* this is how I use the function */
main(){
char *res1 = ""; // empty string 1
char *res2 = ""; // empty string 2
strAddChar( res1, ''a'' );
strAddChar( res1, ''b'' );
strAddChar( res1, ''c'' );
strAddChar( res2, ''1'' );
strAddChar( res2, ''2'' );
strAddChar( res2, ''3'' );
printf( "%s\n",res1 ); // test
printf( "%s\n",res2 );
Ok, the output should be res1="abc" and res2="123" but this is my result :
res1="abc" res2="bc123"
How does "bc" come in res2?? How to fix the function?
Greetings,
Rick
推荐答案
您是否调查了strcat()和strncat()?
-
Andreas K?h?ri
Did you investigate strcat() and strncat()?
--
Andreas K?h?ri
这篇关于将字符添加到字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!