DEV Community

GUSBOi・乇义乇
GUSBOi・乇义乇

Posted on

Strings in C

Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’.

Declaration of strings: Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string.

the number of characters strings will store. Please keep in mind that there is an extra terminating character which is the Null character (‘\0’) used to indicate the termination of string which differs strings from normal character arrays.

Initializing a String:

  1. char str[] = "Helloworld";

  2. char str[50] = "Helloworld";

  3. char str[] = {'H','e','l','l','o','w','o','r','l','d','\0'};

  4. char str[14] = {'H','e','l','l','o','w','o','r','G
    l','d','\0'};

We can see in the above program that strings can be printed using normal printf statements just like we print any other variable. Unlike arrays, we do not need to print a string, character by character. The C language does not provide an inbuilt data type for strings but it has an access specifier “%s” which can be used to directly print and read strings.

example program:

include

int main()
{

// declaring string
char str[50];

// reading string
scanf("%s",str);

// print string
printf("%s",str);

return 0;
Enter fullscreen mode Exit fullscreen mode

}

Top comments (0)