Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Language Examples - Copy a String

C Language Examples - Copy a String

C Language Examples C Language Examples

Copy the string from one variable into another.

Example - Using strcpy()

#include

<

stdio.h

#include

<

string.h

int

main

(

)

{

char

src

[

40

]

;

char

dest

[

100

]

;

memset

(

dest

, '\

0

',

sizeof

(

dest

)

)

;

strcpy

(

src

,

"

This is runoob.com

"

)

;

strcpy

(

dest

,

src

)

;

printf

(

"

Final destination string: %s

\

n

"

,

dest

)

;

return

(

0

)

;

}

The output is:



最终的目标字符串: This is runoob.com

Example - Without using strcpy()

#include

<

stdio.h

int

main

(

)

{

char

s1

[

100

]

,

s2

[

100

]

,

i

;

printf

(

"

String s1:

"

)

;

scanf

(

"

%s

"

,

s1

)

;

for

(

i

=

0

;

s1

[

i

]

!= '\

0

'; ++

i

)

{

s2

[

i

]

=

s1

[

i

]

;

}

s2

[

i

]

= '\

0

';

printf

(

"

String s2: %s

"

,

s2

)

;

return

0

;

}

The output is:



字符串 s1: runoob

字符串 s2: runoob

C Language Examples C Language Examples