C Strings

  • Character array or collection of character or group of characters are called string.
  • In implementation when we required char, array operations then recommended to go for string.
  • Within the single quotation any content is called character constant.
  • Always character constant returns an integer value.
  • Within the double quotes any content is called string constants.
  • Syntax:

    char str[size];

    Example:

    char str{4];
    size–4
    sizeof(str)–>4B

    String Declaration Rules:

    In declaration of strng size must be required to mention otherwise it gives an error.

  • In declaration of the string size must be unsigned integer value which is greater than zero(0). Following are invalid
  • char str[];
    char str[0];
    char str[-1];
    char str[-199];

  • In initialization of the string, if specific number of characters are not initialized it. Then, rest of all characters will be initialized with null.
  • In initialization of the string, we cant initialized more than size of string elements. Following declaration is error.
  • char str[1]={‘a’,’b’,’c’} –> Error

  • In initialization of the string mentioning the size of is optional, in this case how many elements are there initialized it, that array element be created.
  • char str[]={‘a’,’b’,’c’,’d’}; –> Valid declaration

  • When we are working with strings, always recommended to initialize the string content within double quores(“”) only.
  • When we are working with character array explicitly null character doesn’t occupies any physical memory at the end of the char, array.
  • When we are working with string data at the end of string null char will occupies physical memory.

Examples:

#include
#include
int main()
{
char str[5]={‘K’,’2′,’S’,’C’,’H’};
char near *ptr = (char near * ) null;
ptr=&str[0];
++ptr;
–*ptr;
–ptr;
++*ptr;
printf(“%c%c”,str[0],str[1]);
getch();
return 0;
}

Following are the string functions:

strcat( )
stricmp()
strcmp()
strlwr()
strupr()
strrev()
strlen()
strcpy()

Powered by k2schools