Strings in C

A string is an Arrayof characters.We have used strings in a number of examples in the past.Any group of characters defined between double quotation marks is a constant string.
Out put the string is Hello.
Character strings are often used to build meaningful and readable programs. The common operations performed on character strings are:
  • Reading and writing strings
  • Combining strings together
  • Copying one string to another
  • Comparing strings for equality
  • Exatracting a portion of a string

Declaring and Initialization string variables

There are twoways to declare strings in c langauge.
  1. By char Array
  2. By string literal
A string variable is any valid C variable name and is always declared as an arrya. The general form of declaration of a string variable is
char string_name[size]
The size determines the number of characters in the string-name.Some examples are
char city[10];
char name[30];
when the compiler assigns a character string to a character array, it automatically supplies a null character at the end of the string.There fore the size should be equal to the maximum number of characters in the string plus one. String by String literal
Synatx: char ch[]="hello";
NOTE: \0 is the not necessary c inserts the null character automatically.The %s is used to print string in c.

String Handling Functions

The c library supports a large number of string-handling functions that can be used to carry out many of the string manipulations discussed so far.Following are the most commonly used string functions.
Function Action
strcat() Concatenates two strings
strcmp() compares two strings
strcpy() copies one string over to another
strlen() finds the length of a string
we shall discuss briefly how each of these functions can be used in the processing of strings.

Strcat() Function

The strcat() function joins two strings together.And result is returned to first string. Syntax:
First_string and Second_string are character arrays. When the function strcat is executed, second_stringis appended to
first_string. it does so by removing the null character at the end of first_string and placing Second_string from there.The string at Second_stringremains unchanged. Example:
int main()
char first_string[10]={'h','e','l','l','o',' ','\0'};
char second_string[10]={'w','o','r','l','d','\0'};
strcat(first_string, second_string);
printf("value of first string is :%s",first_string);

Post a Comment