728x90 AdSpace

Trending

Strings in c



Basics 

 1 . creating object or allocating memory for a normal variable

             char i;
initial : 
             when program compiled then memory will be allocated for an character variable i.
            pictorial representation : 
2. initialization of character variable 
          2.  1 . statistical initialization
            def : assigning a character , to character variable during compilation time .
           as we assign an integer to integer variable we can't assign a character directly to character                         
       variable.
       char i;
        i=a; // illegal statement which leads to compilation error
WHY ABOVE STATEMENT LEADS TO COMPILATION ERROR ?
during compilation time compiler treats i and a as variables but a is not declared .so lead to compilation error .
To over come above error single coat's are used  to assign a character ,  to character variable as show below  .
        char i;
        i='a';
       2. 2. dynamic initialization
         def : assigning a character , to character variable during run time
        we can use scanf to store a character into character variable which is show below : 
        scanf("%c",&i);
        NOTE : if u try to give more number of characters its will accept only character and remaining 
        character are ignored .

above case usefully but when you want to store more number of variable you should declare more variables . you can reduce your work by using array of character concept.
STRINGS: strings are nothing but array of character or group of character  which are under a single variable name .
to use any variable we need to create it before using.
char a[10];// creating character array variable or object
memory representation : 

Memory details : 
when above piece of code is compiled then compiler will allocate 10 bytes of memory .
in above case (char i) compiler allocates only one byte so you can store only one character .but in this case compiler allocates 10 bytes of memory so we can store 10 characters.
all the memory allocated are in consecutive location , which means if address of first is 1000 
then next cell address  will be 1000+sizeof(char)=(1001).which is show in below .
memory allocation : 

HOW TO STORE OT ASSIGN CHARACTERS TO AN ARRAY VARIABLE ?
 initialization of character variable 
            1 . statistical initialization
            before going to initialization we need to know how to access the memory location .
            generally if you declare a character variable , then there will be a memory location for that
            variable  we can access that memory location directly with  variable name .but in array of   
           character .generally variable name represents .memory location of first cell  , which is
           generally called as Base address .
      if we know base address of any array variable we can access remaining location or cells by   
     increment the address or we can access directly as show below .
a[0] points to first cell ,a[1] points to second cell and so on.
memory locations :


0, 1, 2, 3, ...9 are called index values.

generally index values start from 0 to n-1 // where n represents size .here n=10;

as we assign a character , to character variable similar way we can assign character to array which is shown below.
1.assigning character individually :  
a[0]='a'; a[1]='b';

if you initialize characters individually then we need to place NULL character at end.
{  NULL :  '\0' }
NULL generally represents terminating condition .   
1.assigning character while creating object or while declaring variable
char a[10]={"HELLO"};// no need of placing null  
in this case mentioning of size is optional so we can write it in this way also as show below   
  char a[]={"HELLO"};// no need if placing null
2. dynamic initialization :it is possible by using scanf and other inbuilt library function  .
printing array of character : 
we can use printf : printf("%s",a);
we should not give &a in printf because '   a ' its self represents the address.
or by using  looping structures .
   for(i=0;a[i]!=NULL;i++)
         printf("%c",a[i]);  

String manipulation
as we do some operation on array of integers like merging , sorting ,finding max number , min number like soon..
we can also perform different operation on strings.
To perform operations on array of integers we need to write the logic but to perform some basic operations on strings some inbuilt function are available we can use it other wise we can write logics to perform operations.
DIFFERENT OPERATION WHICH CAN BE DONE ON STRINGS  :

  • we can combine two strings.
  • we can compare to strings. 
  • we can copy one string to another string .
  • we can find length of string.
and many more...
to perform above operation C compiler provides inbuilt function.
1.combining of two strings .
generally this operation is know as string concatenation or appending of strings.
library funtion : strcat(str1,str2); 

from above diagram :  strcat(a,b); then string b is combined with a and final results stores in a .
try this code to get more clarity about strcat function.
/**program to concatenate two strings **/

#include 
int main() {
  char string1[10];
  char string2[20];
printf("enter two strings  :" );
scanf("%s",string1);
scanf("%s",string2);
   strcat( string1, string2 );
  printf("Concatenated String : %s\n", string1 );
  return 0;
}
output
enter two strings
hello
world
concatenated string : helloworld
2.String length 
: to know length of a particular string.
syntax :  strlen(string name); function returns length of string
--------------------------------------------------------------------------------------
#include 
int main()
{
  char s[20] = "HELLOWORDLD";
  printf("The length of \"%s\" is %d characters.\n", s, strlen(s));
  return 0;
}output : The length of "HELLOWORLD" is 11 characters.
-------------------------------------------------------------------------
function counts one by one character until it reaches NULL character and returns counted value which generally represents the length of the string .

3.coping of strings
copying if one string into another string .to get more clarity see below pic.
  
---------------------------------------------------------------------------------------------------
/* program which copies string */
#include 
#include 

int main ()
{
  char str1[]="Sample string";
  char str2[40];
  char str3[40];
  strcpy (str2,str1);
  strcpy (str3,"copy successful");
  printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
  return 0;
}ouput :


str1: Sample string
str2: Sample string
str3: copy successful
---------------------------------------------------------------------------------------------------
4.comparing of two strings : 
string comparison can be done by using strcmp function .

Return Value

  • if Return value if < 0 then it indicates string1 is less than string2
  • if Return value if > 0 then it indicates string2 is less than string1
  • if Return value if = 0 then it indicates string1 is equal to string2

use this function strcmp(a,b);
in above case first a[0] of string a is compared with a[0] of string b 
ASCII values of m is greater than h  so it returns less than o value.
NOTE if  ASCII value of a[0] of both the string are equal  then strcmp function compare next character .returns respective to the ASCII value for more information about ASCII value see above pic.
/**sample program which compare one string to another */

#include 

int main() {
  char string1[20];
  char string2[20];
  strcpy(string1, "Hello");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strcmp( string1, string2));
  strcpy(string1, "Helloooo");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strcmp( string1, string2));
  strcpy(string1, "Hellooo");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strcmp( string1, string2));
  return 0;
}output : Return Value is : -111
Return Value is : 111
Return Value is : 0
STRING INPUT OUTPUT FUNCTIONS : 
printf , scanf , gets , puts , getchar , putchar and so on ..
i think there is no need of discussion on printf and scanf functions.
WHY gets INSTATD OF USING scanf ? 
observe the following code .
int main()
{
char a[20];
printf("enter string : ");
scanf("%s",a);
printf("entered string is %s",a);
return 0;
}
ouput : enter string : hello world
entered string is hello
**from above output we observed that  even though we enterd hello world as input but it accepts hello as input and ignored remaining charecter. 
from this we can conclude that terminating condition for scanf is space (white space).
so if you want to include space in the string then use gets instead of scanf.
puts : puts is similar to printf to print the string on the screen.
generally when we use gets to accept string in any program we will use puts to print the stirng.
gets and puts will accept a argument .see below code
/* program which demonstration gets and puts function */
int main()
{
char a[20];
puts("enter string : ");
gets(a);
puts(a);
return 0;
}
ouput : enter string : hello world
entered string is hello
as we use gets and puts function for string input and output there are two more function 
getch and getchar function to accept character.
observe below code : 
int main()
{
char a;
printf("enter character : ");
scanf("%c",a);
printf("entered character is %c",a);
return 0;
}
output : enter character : m
entered character : m
**from above output we observed that when you press character it is visible and scanf won't accept the the character until enter is pressed.
if you don't want to print character when entered and to  accept  character with out pressing   enter or any character we will use getch function.
observe below code :  
int main()
{
char a;
printf("enter character : ");
    a=getch();//function returns the accepted character
printf("entered character is %c",a);
return 0;
}output : enter character : 
entered character : s
getchar will work same as getch but it will wait until enter or any character is pressed and character is vissible on the screen.

/* sample code on getchar */
int main()
{
char a;
printf("enter character : ");
a=getchar();
printf("entered character is %c",a);
return 0;
}
output : enter character : m
entered character : m
*********************************************************************************************
hope you get a clarity about strings after reading it//
Stay connected..!
Strings in c Reviewed by B AProgrammer on 07:39 Rating: 5 Basics   1 . creating object or allocating memory for a normal variable              char ...

No comments: