C

String and Character array

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.


Declaring and Initializing a string variables

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.


String Input and Output

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();
}

Output:

Command Prompt
Enter a string:
Tutorialink
Entered String is: Tutorialink

String Handling Functions

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() function

strcat("hello","world");

strcat() function will add the string "world" to "hello".


strlen() function

strlen() function will return the length of the string passed to it.

int j; 
j = strlen("Tutorialink");
printf("%d",j);

Output:

Command Prompt
11

strcmp() function

strcmp() function will return the ASCII difference between first un-matching character of two strings.

int j; 
j = strcmp("Tutorial","Ink");
printf("%d",j);

Output:

Command Prompt
-1



Subscribe us on Youtube

Share This Page on

Question


alpesh lathiya | 19-May-2016 05:07:40 pm

Sir tamari site wechwani 6????


Ask Question