Strings in C



Concept


A string is a 1D array of characters terminated by a NULL character ('\0'). 
  0   1   2   3   4   5   6    7
 ________________________________
| P | r | o | g | r | a | m | \0 |
|___|___|___|___|___|___|___|____|


Syntax 


Declaring a string

char str[8];
str is the name of the string variable.str can store only 7 letters.1 byte is needed to store NULL character.

str stores the base address of a string.It is a constant pointer to the 0th element of string.

Initializing a string

char str[] = "Program";
You can access the string elements by str[i].
You can manipulate string element by saying str[i] = 'C'

char* str = "Program"
str is a pointer to string Program.
This will allow you to access the string but not manipulate string elements.


Accept a string from user

scanf("%s",str);
%s is format specifier for string.
But scanf cannot accept multiword string.So we use a library function 
gets(str);


Print a string 

printf("%s",str);
puts(str);
But puts cannot print a multiword string and it places the control on the next line.


Commonly used string functions


strlen(s)                                   Returns the length of string s (excludes null character).

strcat(dest,source)               Appends a copy of source to the end of dest.

strcpy(dest,source)              Copies source to dest.

strcmp(s1,s2)                         Returns 0 if s1==s2, <0 if s1<s2, >0 if s1>s2

strrev(s)                                  Reverses string s.


More


Without using library functions


No comments:

Post a Comment