C Tutorial/String/String Introduction

Материал из C\C++ эксперт
Версия от 10:32, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A string is an array of characters.

#include <stdio.h>
int main(){
   char myname[] = "Dan";
  
   printf("%s \n",myname);
}
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.


#include <string.h>    
    int main() 
    {  
        char    name[4];   
        strcpy(name, "Sam");
        return (0);    
    }

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.


#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);
}
abcd          4206592
efgh          2293584
efgh          2293584
efgh          2293584

Strings always end with the NULL character

ASCII code for the NULL character is \0


#include <stdio.h>
int main(){
  char myname[4];
    myname[0] = "D";
    myname[1] = "a";
    myname[2] = "n";
    myname[3] = "\0";
    printf("%s \n",myname);
}
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

#include <stdio.h>
int main(){
    char myname[] = { "D", "a", "n" };
    printf("%s \n",myname);
}
Dan?