C Tutorial/String/String Introduction

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

A string is an array of characters.

<source lang="cpp">#include <stdio.h> int main(){

  char myname[] = "Dan";
 
  printf("%s \n",myname);

}</source>

Dan

String constants consist of text enclosed in double quotes

We must use the standard library function strcpy to copy the string constant into the variable.

To initialize the variable name to Sam.


<source lang="cpp">#include <string.h>

   int main() 
   {  
       char    name[4];   
       strcpy(name, "Sam");
       return (0);    
   }</source>

Strings

  1. A string is nothing more than a character array.
  2. All strings end with the NULL character.
  3. Use the %s placeholder in the printf() function to display string values.


<source lang="cpp">#include <stdio.h> main ( ) {

   char *s1 = "abcd";
   char s2[] = "efgh";
   printf( "%s %16lu \n", s1, s1);
   printf( "%s %16lu \n", s2, s2);
   s1 = s2;
   printf( "%s %16lu \n", s1, s1);
   printf( "%s %16lu \n", s2, s2);

}</source>

abcd          4206592
efgh          2293584
efgh          2293584
efgh          2293584

Strings always end with the NULL character

ASCII code for the NULL character is \0


<source lang="cpp">#include <stdio.h> int main(){

 char myname[4];
   myname[0] = "D";
   myname[1] = "a";
   myname[2] = "n";
   myname[3] = "\0";
   printf("%s \n",myname);

}</source>

Dan

Useful string function

Function Description strcpy(string1, string2) Copy string2 into string1 strcat(string1, string2) Concatenate string2 onto the end of string1 length = strlen(string) Get the length of a string strcmp(string1, string2) 0 if string1 equals string2, otherwise nonzero

Write string in a more traditional array style

<source lang="cpp">#include <stdio.h> int main(){

   char myname[] = { "D", "a", "n" };
   printf("%s \n",myname);

}</source>

Dan?