C/String/String Copy

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

A simple string copy

<source lang="cpp">

  1. include <stdio.h>
  2. include <string.h>

int main(void) {

 char str[80];
 strcpy(str, "this is an example");
 puts(str);
 return 0;

}

      </source>


Copy a string

<source lang="cpp">

  1. include <stdio.h>
  2. include <string.h>

int main(void) {

 char str[80] = "I like C";
 strcpy(str, "I like Java");
 printf(str);
 return 0;

}

      </source>


Copy characters from one string to another: how to use strncpy

<source lang="cpp">

  1. include <stdio.h>
  2. include <string.h>

int main () {

 char str1[]= "Hi Hello and ";
 char str2[6];
 strncpy (str2, str1, 5);
 str2[5] = "\0";
 puts (str2);
 return 0;

}

      </source>


Copy string: how to use strcpy

<source lang="cpp">

  1. include <stdio.h>
  2. include <string.h>

int main () {

 char str1[]="Sample";
 char str2[40];
 char str3[40];
 strcpy (str2, str1);
 strcpy (str3, "copy");
 printf ("str1= %s\n str2= %s\n str3= %s\n", str1, str2, str3);
 return 0;

}

      </source>


how to use strcpy (string copy)

<source lang="cpp">

/*

Practical C Programming, Third Edition By Steve Oualline Third Edition August 1997 ISBN: 1-56592-306-5 Publisher: O"Reilly

  • /
  1. include <string.h>
  2. include <stdio.h>

char name[30]; /* First name of someone */ int main() {

   strcpy(name, "Sam");    /* Initialize the name */
   printf("The name is %s\n", name);
   return (0);

}


      </source>


String copy: assign the pointer value

<source lang="cpp">

  1. include <stdio.h>
  2. include <string.h>

int main(void) {

 char *p = "stop";
 char str[80];
 do {
  printf("Enter a string: ");
  gets(str);
 } while(strcmp(p, str));
 return 0;

}


      </source>