String in C

String in C

string in c

String in C:-

A string in C is a character array terminated with a null character.

All the string are character array but all the character array is not a string.

main()

{
            char p[]={‘a’,’b’,’c’,’d’};

            char q[]={‘a’,’b’,’c’,’d’,’\0’};
}

Here p is character array and q is a string.

 

Anything is written within a double code that is known as the string constant.

Ex:-

main()

{
     char p[]={‘a’,’b’,’c’,’d’,’\0’};

     char q[]=”abcd”;
}

Here p and q both are same but most appropriate declaration is q.

Here q is string constant.

 

Here some important string functions are used.

Strlen:-

Strlen measures the length of the string without null character.

main()

{

   char r[]="abc";

   printf("%d %d",strlen(r));

}

Size_of:-

Size_of measure the length of the string including null character.

main()

{

    char r[]="abc";

   printf("%d %d", sizeof(r));

}

 

Strcpy:-

strcpy copies the entire string including null character.

main()

{

    char x[20];

    strcpy(x,"c program");

    printf("%s",x);

}

Strncpy:-

strncpy only copy no. of character except null character.

main()

{

    char x[20];

    strncpy(x,"c program",4);

    printf("%s",x);

}

Strcmp:-

Strcmp is used to compare two string.

main()

{

   char x[]="Abc";

   char y[]="abc";

   int k=strcmp(x,y);

   if(k==0)

    {

       printf("same");

    }

    else

    {

     printf("different");

    }

}

Strcat:-

Strcat command is used to concat the string.

main()

{

   char x[30]="abc";

   char y[20]="def";

   strcat(x,y);

   printf("%s",x);

}
basicittopic

basicittopic

A Computer Science Study for IT students and people of IT community