字符串复制函数
#include <stdio.h>
void str_copy(char t[], const char s[])
{
int i;
while (s[i] != '\0')
{
t[i] = s[i];
i++;
}
t[i] = '\0';
for(i = 0; t[i] != '\0'; i++)
printf("%c", t[i]);
}
/*以上函数更紧凑的写法*/
void str_copy_2(char t[], const char s[])
{
int i = 0;
while(t[i] = s[i]) i++; /*赋值表达式的值就是被赋的值*/
for( i = 0; t[i] != '\0'; i++)
printf("%c", t[i]);
}
/*类似的简写法*/
/*
int c;
c = getchar();
while(c != EOF);
简写:
int c;
while ((c = getchar()) != EOF)
*/
int main()
{
char s[] = "Peking University";
char t[18];
str_copy_2(t, s); /*str_copy_2(t, s + 3)亦可*/
return 0;
}
指针法,与其上的写法比较
#include <stdio.h>
void str_copy(char *t,const char *p)
{
while(*t = *p)
{
t++;
p++;
}
}
int main()
{
char s[] = "Peking University";
char t[19];
int i;
str_copy(t, s+3);
for(i = 0; t[i] != '\0'; i++)
printf("%c", t[i]);
return 0;
}

被折叠的 条评论
为什么被折叠?



