我自己的连接函数不会更改目标字符串
My own concatenate function doesn't change destination string
我试过调试这段代码,但即使在while循环中循环字符串,看起来也没有循环任何内容。调用函数后,目标数组保持不变。
void stringConcatenate(char * destination, char * source)
{
int index1 = 0; //for cycling subscripts
int index2 = 0;
while (destination[index1] != ' ') //cycle to end of first string
{
index1++;
}
index1++; //to get to null character
while (source[index2] != ' ') //cycle through second string appending along the way
{
destination[index1] = source[index2];
index1++;
index2++;
}
destination[index1] = ' '; //append null point
}
在第一个while
语句之后递增index1
的行不应该存在。
index1++; //to get to null character <-- incorrect.
index
已经指向终止符。通过在那里递增它,您最终会在结束符之后追加字符串一个字符。
还有另一种使用指针连接两个字符串的方法,您也应该尝试一下。
#include<stdio.h>
void concat(char* ,char* );
void main(void)
{
char str1[25],str2[25];
printf("nEnter First String:");
gets(str1);
printf("nEnter Second String:");
gets(str2);
concat(str1,str2); //1
printf("nConcatenated String is %s",str1);
}
void concat(char *s1,char *s2)
{
while(*s1!=' ') //2
s1++
while(*s2!=' ') //3
{
*s1=*s2; //4
s1++;
s2++;
}
*s1=' '; //5
}