C Tutorial/String/String Copy

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Copying a string using array notation and pointer notation

#include <stdio.h>
void copy1( char *s1, const char *s2 ); 
void copy2( char *s1, const char *s2 ); 
int main()
{
   char string1[ 10 ];          
   char *string2 = "Hello";     
   char string3[ 10 ];          
   char string4[] = "Good Bye"; 
   copy1( string1, string2 );
   printf( "string1 = %s\n", string1 );
   copy2( string3, string4 );
   printf( "string3 = %s\n", string3 );
   return 0;
}
void copy1( char *s1, const char *s2 )
{
   int i;
   for ( i = 0; ( s1[ i ] = s2[ i ] ) != "\0"; i++ ) {
      ;   
   } 
}
void copy2( char *s1, const char *s2 ) {
   for ( ; ( *s1 = *s2 ) != "\0"; s1++, s2++ ) {
      ;   
   } 
}
string1 = Hello
string3 = Good Bye

Take a first name and a last name and combines the two strings

#include <string.h>
    #include <stdio.h>
    int main()
    {
        char first[100];
        char last[100];
        char full_name[200];

        strcpy(first, "first");
        strcpy(last, "last");
        strcpy(full_name, first);

        strcat(full_name, " ");
        strcat(full_name, last);
        printf("The full name is %s\n", full_name);
        return (0);
    }
The full name is first last