Strings



Strings are derivative data type of char data type , strings are used to store piece of text , name , address and so on 
We can say that strings are sequence of character that is terminated by a null character which is  \0 , 

well null character is a special character that signify the end of the string

Now let us see how to declare a string and use it in a program

Char name[20];

This is a string of char type of size 20 , means the name variable can store up to 19 character in a sequence , Why 19 because the last place is already occupied by the null character , so in order to allocate exact size we always give the size of the string one more then the desired value , so if we look at our old box example the above will look like something




 
There are two ways we can assign value to a string one is at the time of declaration and one is user input, let us see the former one first

Char name[20]  =  “hello world”;

We can also use a function to copy a value in a string

strcpy(name,”hello world”);

here strcpy is a function and name is the string name and the "hello world" is the content that we want to write to the string

To display a string we use %s and string name

printf(“name of the string is %s”,name);

there are many ways of handling a string but for now we will just focus on these for simplicity ,

To accept values from a user to a string we write

Scanf(“%s”,string_name);

String is the only data type in which we do not need the ampersand sign
But there is a problem in this , if you write something like “hello world” the string will only read to the word hello and when it find the white space it will stop , 

so in order to prevent this and command the scanf to scan to the end of the string we write

scanf(“%[^\n]”,string_name);

I know it looks difficult but the following program will make it easy

main()
{
char string_one[100];
printf("Please Enter Your Full Name \n");
scanf("%[^\n]",string_one);   
printf("your name is .....%s\n",string_one);
getch();
}

This program accepts your full name , store it in a string , and display the output

No comments:

Post a Comment