【发布时间】:2017-10-25 05:10:16
【问题描述】:
我正在尝试这个输出:
Comparing results of concat and strcat ...
strcmp("Plain old stringTroy", "Plain old stringTroy") says: 0
如果两个字符串参数相同,则 strcmp 返回 0。如果结果为 0,则 concat 的行为与库函数 strcat 完全相同。
这就是我所拥有的 concat 方法。
#define MAXSIZE 32
void concat(char dest[], char src[])
{
int i=length(src);
int j=0;
for(j; j<src[j] !='\0'; j++) {
dest[i+j] = src[j];
}
dest[i+j] = '\0';
}
长度方法是:
int length(char str[])
{
// Add code here to return the length of the
// string str without using the strlen function
// Do not count the null character '\0'
// in computing the length of the string
int len=0;
int i;
for(i=0;i<str[i];i++) {
len++;
}
return len;
}
这是我的主线
int main()
{
// Variable declarations for all parts
char str2[] = "Troy";
char str4[] = "Plain old string";
char str6[MAXSIZE];
// Part 6
printf("\n----- Part 6 -----\n");
// Make a copy of the destination string first, to be reused later
strcpy(str6, str4);
concat(str4, str2);
strcat(str6, str2);
printf("Comparing results of concat and strcat ...\n");
printf("strcmp(\"%s\", \"%s\") says: %d\n",
str4, str6, strcmp(str4, str6)
);
return 0;
}
这是我运行时的输出:
----- Part 6 -----
Comparing results of concat and strcat ...
strcmp("PlaiTroy", "Plain old stringTroy") says: -1
第一个字符串与第二个字符串不同,这就是我得到 -1 的原因。我的问题出在我的 concat 方法中,但我似乎无法理解为什么它不能很好地执行。是因为空格吗? 0 和 '\0' 执行不好吗?
【问题讨论】:
-
j<src[j] !='\0'这是一个奇怪的情况。不就是src[j] !='\0' -
也在你的 len 方法中
i<str[i]???应该是for(i=0;str[i];i++) -
数组
str4有 17 个字符的空间,包括终止符。想想当您使用str4作为目标字符串时,concat函数中会发生什么。 -
@MillieSmith 你不必说服 我 代码是错误的 :)
-
@Someprogrammerdude 我们也不知道
MAXSIZE是否足够大。