home > 写経編 > 柴田望洋『明解C言語 入門編』 > 11. 文字列とポインタ >

ForNext

Only Do What Only You Can Do

085. 文字列のコピー

VBScript

JScript

Perl

PHP

Python

Ruby

PowerShell

Scala

F#

C

更新日 : 2010.10.08
#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;
}
R:\>lesson085\project1.exe
st1 = 12345
st2 = ABC

st1 = ABC 5
st2 = ABC

st1 = ABC 5
st2 = ABC

C++

C++Builder

VC++

C#

Java

Objective-C

D

VB

VB.NET

Delphi

更新日 : 2010.09.24
program Project1;

{$APPTYPE CONSOLE}

uses
    SysUtils;

function str_cpy(d:PChar; s:PChar):PChar;
begin
    result := d;

    repeat
        d^ := s^;
        Inc(s);
        Inc(d);
    until (s^ = #0);

    d^ := s^; { \0 も COPY }
end;

procedure main();
const
    st1: String                = '12345';
    st2: String                = 'ABC';

    pt1: array[0..255] of Char = '12345';
    pt2: array[0..255] of Char = 'ABC';
var
    i: Integer;
begin
    Writeln(Format('st1 = %s', [st1]));
    Writeln(Format('st2 = %s', [st2]));
    Writeln('');

    st1 := st2;
    Writeln(Format('st1 = %s', [st1]));
    Writeln(Format('st2 = %s', [st2]));
    Writeln('');


    Writeln(Format('pt1 = %s', [pt1]));
    Writeln(Format('pt2 = %s', [pt2]));
    Writeln('');

    str_cpy(pt1, pt2);
    write('pt1 = ');
    for i := 0 to 4 do
        if pt1[i] = #0 then
            write(' ')
        else
            write(pt1[i]);
    Writeln('');
    Writeln(Format('pt2 = %s', [pt2]));
    Writeln('');


    pt1 := '12345';
    Writeln(Format('pt1 = %s', [pt1]));
    Writeln(Format('pt2 = %s', [pt2]));
    Writeln('');

    StrCopy(pt1, pt2);
    write('pt1 = ');
    for i := 0 to 4 do
        if pt1[i] = #0 then
            write(' ')
        else
            write(pt1[i]);
    Writeln('');
    Writeln(Format('pt2 = %s', [pt2]));
    Writeln('');
end;

begin
    main;
end.
S:\>lesson085\project1.exe
st1 = 12345
st2 = ABC

st1 = ABC
st2 = ABC

pt1 = 12345
pt2 = ABC

pt1 = ABC 5
pt2 = ABC

pt1 = 12345
pt2 = ABC

pt1 = ABC 5
pt2 = ABC

Ada

PL/SQL

T-SQL

関数型

inserted by FC2 system