Wednesday, 14 March 2012

Strings


There is no String data type in C.
Strings in C are simply arrays of characters terminated with ‘\0’ (null character)
NULL terminates a string.
        This null character has ASCII value 0.
Terminating null is important as it’s only way  to tell where string ends.Infact,string not terminated by ‘\0’ is not really a string but merely collection of ch’s.
1 dim array of chracters(special kind of
array)
String Initialization
Like var’s  Ch. Arrays must be declared before they appear in progr
am.
Character Array can b
// one way
                                  char nam
char msg[6] = {‘H’,‘e’,‘y’,‘ ’,‘!’,‘\0’};
Initilization to each element of ch array is made by assigning ch constant enclosed within single quotes.
// another way :
Here chs are not initialized individually.It auto adds null ch to end of string.
char msg[8] = “Hey !”; // no ‘\0’
// or
char msg[ ] = {“Hey !”}; // no ‘\0’  
memory for 6 characters ( 5 plus the null char ‘\0’ ) automatically allocated

Note:Declare size of arrays as 1 more than no of ch to be received so as to accommodate null ch(‘/0’)
Memory Representation
Each ch  occupies 1 byte of mem. And last ch is always ‘\0’

.E.g: “computer” is string of 8 chracters This is stored in ram as:
e[20];

4001-c(ch[0])
4002-o(ch[1])
4003-m
4004-p
4005-u
4006-t
4007-e
4008-r
4009-/0(ch[9])
Very 1st ch. Occupies 0 subscript,2nd  ch occupies 2nd and so-on last ch (n-1)subscript in an n-ch array.Each ch in an array occupies 1 byte of mem.Elements of ch arrays are stored in contiguous mem loc.
 Input and Output of String(Reading n writing strings)

READING STRINGS:
1. scanf()
2.gets()
3. getchar()
Writing Strings:
1. printf()
2.puts()
3. putchar()
Strings can be read in or written out using i/p-o/p stats.
1. Using scanf() and printf() methods
  char name[20];
   scanf(“%s”, name);//passing base add of array
Note:scanf() auto puts null ch at end of input.
  2.  printf(“%s”, name);
3. Using gets() and puts() methods
  char name[20];
   gets(name);
Scanf() is not capable of receiving multi-word strings.e.g-’ram roy’ would be unacceptable.But gets fx solve this problem.
Fx  gets() takes in all ch’s from keyboard untill ENTER is pressed.It puts all ch’s  in contiguous mem loc beginning at address is passed. It doesn’t put ENTER ch. in an array but puts null ch instead.
  4.  puts(name);
-displays string by passing add of array
-nth array contains (n+1)array elements

No comments:

Post a Comment

Total Pageviews

Powered by Blogger.