\0 is null character.
Null Character-- Null character is used to denote string termination characters are stored in contiguous memory locations.
A string is stored just like an array in the memory.
A string can be printed by character using printf and %c. But there is another convenient way to print a string.
char s[] = "Tushar"; printf("%s",s);
we can use %s with scanf to take string input.
char s[50]; scanf("%s",s);
Note-scanf can't be used in input multi word strings with spaces
gets() is a function which can be useed to recieve a multi-word string with spaces.
puts() can be used to output a string.
char *ptr = "tushar";
this tells the compiler to store the string in memory and assigned address is stored in a char pointer.
- Note
- Once a string is defined using char st[]="Tushar", it can't be initialized to something else.
- A string defined using pointers can be reinitialized.
ptr = "Tushar";
Used to count the number of characters in the string excluding the null \0 character.
int length = strlen(st);
Used to copy the content of second string into first string passed to it.
strcpy(st2,st);
Used to concatenate two strings
Used to compare two strings.
It returns: 0 if strings are equal
negative value: if first string mismatching character's ASCII value is not greater than second string's corresponding mismatching character.
otherwise it returns positive value.
strcmp("for","joke") -- positive value strcmp("joke","for") -- negative value
A formatted string can be created with the sprintf() function. This is useful for building a string from another data types.
char a[] = "HEllo"; char s[100]; int n = 75; sprintf(s,"%s %d",a,n); printf("%s\n",s);
sscanf is used for scanning a string for values the function reads values from a string and stores them at the corresponding variable addresses.
- Write a program to take string as an input from an user using %c and %s. Confirm that the strings are equal.
- Write your own strlen() function.
- Write a function slice() to slice a string. It should change the original string such that it is now the sliced string.Take m and n as the start and ending position for slice.
- Write your own version of strcpy() function from < string.h >
- Write a program to encrypt a string by adding 1 to the ASCII value of its characters.
- Write a program to decrypt the string encrypted using encrypte function in problem 5.
- Write a program to count the occurence of a given character in a string.
- Write a program to check whether a given character is present in a string or not.