Strings
In c programming array of characters is called string which is always terminated by null character (/0).
example:-
“tutorials daddy”
here “tutorials daddy” is a string . Whenever compiler encounters with any string , it appends null character at the end of string.
memory representation of string:-
strings are stored in memory in the same way as single dimensional arrays are stored.
declaration and initialization :-
char string[6]={‘h’,’e’,’l’,’l’,’o’,’\o’};
above declaration and initialization declare a string of size 6 byte which consist of string “hello”. As every string has null character at the end of string so the size of array will be one more than the number of character in string. Like in other character number of character in string “hello” is 5 but the size of character array string is 6.
we can also declare and initialize string without mentioning the size of array . below is the declaration of “hello” string without mentioning of size
char string[]={‘h’,’e’,’l’,’l’,’o’,’\o’};
compiler will automatically calculate the number of character in string defined by you and will allocate the memory for same.
We can also declare and initialize a string with pointer.for example
char *str=”hello”;
above statement declare a character pointer str and initialize it with string “hello”;
input string from user
we can accept string as an input from user by using scanf function and %s as an modifier. for example:
#include<stdio.h>
int main()
{
char str[6];
printf(“enter the string”);
scanf(“%s”,str); //getting input string from user
}
outputting string
We can print or outputting a string to terminal by using printf() function and %s as a modifier.
int main()
{
char str[6]={‘h’,’e’,’l’,’l’,’o’,’\o’};
printf(“%d”,str);
}
output of program:- hello
string manipulating functions:-when we write C program we might need to manipulate various strings and to manipulate the strings we might need to write functions for that . Which will be very complex for programmer to write function or logic every time whenever programmer need to manipulate the string. To overcome this C provides various library functions which is defined under header file <string.h>. following are the list and purpose of some of the library function which commonly used
list of functions;
following is the example of use of some of above mentioned functions
#include<stdio.h>
#include<string.h>
int main()
{
char str1[10]=”tutorials”;
char str2[6]=”daddy”;
char str3[16];
/* copy str1 into str3 */
strcpy(str3,str1);
printf(“after copy of str1 to str3 : %s”,str3);
/*concatenate str2 and str3 */
strcat(str3,str2);
printf(“after concatenation of str2 and str3 : %s”,str3);
}
after compiling the above program we will get following output
after copy of str1 to str3 : tutorials
after concatenation of str2 and str3 : tutorials daddy
you can find the complete of functions in C library.