introduction to strings in c

a string is actually called as a character array.to use strings we should link string header file in the beginning of the program. single variable stores single character, so we should use array to store the words are sentences .strings are always ended with null character (\0), because this defines the end of a string array .if there are n characters in a string,the string arrays need size of n+1 because of null character at the end. strings are always enclosed by double quotes and characters are enclosed by single quotes. String are declared exactly same as arrays. Remember the size of character string should be greater at least by 1 as compared to its corresponding string constant being assigned because of null character is automatically declared. below are some examples.

declaration:

char x[5] = "code";

the above example is a string array. in this type of declaration, there is no need of declaring null character, c automatically does for you. the size of the above example is 5 including the null character

char x[5] = {'c','o','d','e','\0'};

by the above example we can understand the concept of null pointer, if we declare the array by single characters we should use single quotes and at last, we should mention null character too.

the control strings for the string variables with input and output statements are "%s" and "%c" and we can include any integers instead of characters.

example:

#include
#include
int main ()
{
char string[5];
string[0] = 'C';
string[1] = '0';
string[2] = 'd';
string[3] = 'e';
printf ("%s", string);
return 0;
}

output:

c0de

assignment of the string during the program:

scanf() can be used to take values during program execution as same as numeric values. we don’t need to use &prefix to the variable to define the address of the variable, because string variables are arrays. The program with scanf is space between the words or string. once scanf() encounters an space ,it ignores the rest of the string.

syntax:

scanf("%s",string)

example:

#include
#include
int main()
{
char string[10];
printf("enter name \n");
scanf("%s",string);
printf("\n%s",string);
}
enter name
learnc
learnc

gets() and puts():

so, to avoid these kind of problems ,we should use gets() and puts() functions.gets() can take a complete string with spaces.gets() is replaced by scanf() function.printf() is replaced by puts(),these both functions do same tasks .but these both gets() and puts() doesn't require any control strings

puts(message);
gets(variable);

lets modify above example

example with gets() and puts();

#include
#include
int main()
{
char string[50];
puts("enter the string");
gets(string);
puts("entered string is");
puts(string);
}

output:

hello
entered string is
hello

there are some string functions in next lessons