文字列のコピー

明解C言語 入門編 > 11. 文字列とポインタ >

文字列のコピー

C


#include <stdio.h>
#include <string.h>

char* str_cpy(char* d, const char* s)
{
char* t = d;

while (*d++ = *s++)
;

return t;
}

int main(int argc, char* argv[])
{
int i;
char* st1 = "12345";
char* st2 = "ABC";

printf("st1 = %s\n", st1);
printf("st2 = %s\n", st2);
puts("");

str_cpy(st1, st2);
printf("st1 = ");
for (i = 0; i < 5; i++)
if (st1[i] == '\0')
putchar(' ');
else
putchar(st1[i]);
putchar('\n');
printf("st2 = %s\n", st2);
puts("");

st1 = "12345";
strcpy(st1, st2);
printf("st1 = ");
for (i = 0; i < 5; i++)
if (st1[i] == '\0')
putchar(' ');
else
putchar(st1[i]);
putchar('\n');
printf("st2 = %s\n", st2);
puts("");

return 0;
}

実行結果

T:\>lesson085\project1.exe
st1 = 12345
st2 = ABC

st1 = ABC 5
st2 = ABC

st1 = ABC 5
st2 = ABC