string is a sequence of characters that is treated as a single data item and terminated by null character'\0'
. Remember that C language does not support strings as a data type. A string is actually one-dimensional array of characters in C language. These are often used to create meaningful and readable programs.
For example : The string "hello world" contains 12 characters including '\0'
character which is automatically added by the compiler at the end of the string.
There are different ways to initialize a character array variable.
char name[12]="Tutorialink"; //valid character array initialization
char name[12]={ 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 'i', 'n', 'k', '\0' }; //valid initialization
Remember that when you initialize a character array by listings all its characters separately then you must supply the '\0'
character explicitly.
You can read character string with white spaces from terminal using gets() function.
Example:
//Write a C Program which get string form User Input.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20];
clrscr();
printf("Enter a string: ");
gets(str);
printf("Entered String is: %s",str);
getch();
}
C language supports a large number of string handling functions that can be used to carry out many of the string manipulations. These functions are packaged in string.h library. Hence, you must include string.h header file in your program to use these functions.
The following are the most commonly used string handling functions.
Method | Description |
---|---|
strcat() | It is used to concatenate(combine) two string |
strlen() | It is used to show length of a string |
strrev() | It is used to show reverse of a string |
strcpy() | Copies one string into another |
strcmp() | It is used to compare two string |
strcat("hello","world");
strcat() function will add the string "world" to "hello".
strlen() function will return the length of the string passed to it.
int j;
j = strlen("Tutorialink");
printf("%d",j);
strcmp() function will return the ASCII difference between first un-matching character of two strings.
int j;
j = strcmp("Tutorial","Ink");
printf("%d",j);
Ask Question