C String

As a group of an integer is called as integer array. Similarly, a group of character is called as character array. A character array is known as String.

For example:

  • Each character occupies one byte of memory.
  • And the last character is always \0.
  • ‘\0’ is called a null character.
  • ASCII value of ‘\0’ is zero.
  • %s is a format specifier use to print a string.

The following figure shows the way a character array is stored in memory.

string example

The elements of the character array are stored in contiguous memory locations. The terminating null \0 is important.

The above example can also be initialized as,

In this declaration \0 is not necessary. C compiler automatically inserts a null character.

Example:

Output:

Program:

Output:

Points to remember:

  • Because given length is not sufficient for given string.
    Actual length of string is 6 (hello(5) + ‘\0′(1) =6). Therefore above initialization is not valid. Hence correct initialization is:

  • Name of the array itself is a constant pointer.
    So it cannot be incremented nor decremented.

Standard Library String Functions:

Every C compiler has many sets of useful string handling functions. There are many important string functions defined in “string.h” library. The following list contain commonly used string functions:

  1. strlen
  2. strrev
  3. strlwr
  4. strupr
  5. strcat
  6. strncat
  7. strcpy
  8. strncpy
  9. strcmp
  10. strncmp
  11. strcmpi
  12. stricmp
  13. strnicmp
  14. strdup
  15. strchr
  16. strrchr
  17. strstr
  18. strset
  19. strnset

From the above list of functions strlen(), strcpy(), strcat(), strcmp() are the most commonly used functions.
Let us study these functions one by one.

 

Ankit Wasankar

Senior Java Developer
Java 11 | Microservices | Reactjs | SQL

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.