strings in c

A string is a sequence of characters that ends with a null (‘\0’) character. When declaring strings in C, you specify the maximum number of characters it can hold. For instance:

char str[10]; This can hold 10 characters, allowing for a string of up to 9 characters plus the null terminator (‘\0’) at the end.

char str[10] = “hello”; Here, a string of 5 characters (“hello”) is assigned to the array which can hold 10 characters.

strings in c
Comparing string to an array of characters:

char str[10] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’}; This array lacks a null terminator at the end.
char str[10] = “hello”; In this case, the null (‘\0’) character is automatically added at the end of the string.

Using the second option (initialization with double quotes) is simpler for storing words or sentences because it automatically includes the null terminator at the end.
Additionally, a character pointer can hold the base address of a string and can perform operations similar to those of an array.

lets write a program to understand how to store and access strings in c:

#include <stdio.h>
int main()
{
         char str[25] = "onesandzeroverse.com";

         printf("the entered string is: %s\n", str);
}

output:

onesandzeroverse.com

string input through scanf:

#include <stdio.h>
int main()
{
         char str[20];
         printf("Enter a string\n");
         scanf("%s", str);

         printf("the entered string is: %s\n", str);
}

output:

Enter a string
hello
the entered string is: hello

The scanf function in C reads input until a whitespace character (like space, tab, or newline) is encountered. This whitespace character is replaced with the null character (‘\0’), terminating the string. When user gives: h e l l o <enter>, scanf takes these sequence of characters and stores in the memory where str locates as {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

However, if you input a sentence with spaces using scanf, it will read only up to the first space, considering it as the end of the string. The characters after the first space are ignored and not stored in the string.
lets give a string with space

output:

Enter a string
hello world
the entered string is: hello

You can see that the characters after space are ignored and not stored in the string. This can be avoiding with small modifications in scanf lets see how can we include space.

#include <stdio.h>
int main()
{
        char str[30];
        printf("enter a string\n");
        scanf("%[^\n]s", str); 

        printf("the entered word is: %s\n", str);
}

output:

Enter a string
hello world
the entered string is: hello world

you can see that space character is also consider and termination point is only at ‘\n’.

Prev << Pointers with 1-D arrays
Next >> 2-D arrays