Chp 9 Puppetting On Strings Flashcards
What are strings?
Character arrays.
What is a string constant?
Its a one dimensional array terminated by a null (‘\0’).
char name[ ] = { ‘B’, ‘i’, ‘p’, ‘u’, ‘\0’}
Null character :
\0 Has two chars but is only 1. \ indicates special char ahead. \0 and 0 are diff. ASCII values 0 and 48 respectively.
What if a string is not terminated by null char?
Then its merely a collection of chars, other than null, functions working with string have no choice to know bout ends.
Initialise a String:
char name[] = “abcdef”;
C inserts a null character automatically.
Memory map of string ‘abcdef’ :
a,b,c,d,e,f,\0
Stored contiguously. 1 char takes 1 byte.
How to print out a string when len is unknown?
while ( i != ‘\0’ )
we can make use of this statement.
OR
while ( *p != ‘\0’ )
Base address:
All notations for element:
We can get it simply by mentioning the name of array.
num[i] = *(num + i) = *(i + num) = i[num]
Format specifier for string:
in printf
and in scanf
and working of scanf with string?
%s
now clue here
scanf( ‘%s’ , name );
is valid as name carries base address, or basically address where we want the string.
When enter key is hit, scanf places ‘\0’ in the array.
Precautions
Scanf and String:
- Length of string should not exceed dimension of character array, as no bound checking, so it might result in overriding imp data.
- scanf() cannot receive multi-word string.
How to deal with limitation of scanf that it cant accept multi word string:
2 ways:
(2 functions in here )
gets().
Receives only one string but it can be multi-word.
Also, puts() : It can display only one string at a time.
And it puts cursor on the next line unlike printf().
OR
scanf( “%[^\n]s”, name );
Pointers and String:
2 options to store the string sorta..
chr str[] = “Hello”;
chr *p = “Hello”;
We cannot assign a string to another. But we can assign a char pointer to another.
str1 = str; /* Error /
p = q; / q is a char pointer, No error */
String once defined can’t be initialised again. Valid for char pointers.
str = "Bye"; /* Error*/ p = "Bye"; /* works */
Standard lib functions:
Check table. for now: strlen(string) strcmp(string,string) strcpy(target,string) strcat()
strlen()
Counts no. of char present in string.
It takes in the base address of string then counts until ‘\0’ encountered and returns length.
It doesn’t count ‘\0’.
strcpy()
strcpy( target, source );
Copies Contents of source in target.
It accepts base address of both strings, string gets copied char by char, no short cut.
Remeber after chars being copied, after loop, target should have ‘\0’ at the end.