PC Unit6
PC Unit6
Definition:
• A string is an array of characters stored in consecutive memory location.
• In strings, the ending character (termination of string) is always the null character ‘\0’.
Declaration:
Syntax:
char stringname[length];
Example:
char str[10];
This example declares an array str which can store at the most 10 characters.
Initialization:
Character array can be initialized in two ways
1. as individual character
2. as single string.
Example:
char str[10]={‘h’,’e’,’l’,’l’,’o’};
char str[10]=”hello”;
char str[]hello”; //this declaration automatically assigns size of array as 6
// including ‘\0’
A string of n elements can hold (n-1) characters , as nth character is always ‘\0’.
The compiler automatically stores null character at the end of the string.
Memory Representation:
Str[0] Str[1] Str[2] Str[3] Str[4] Str[5]
H L \0
E L O
100 101 102 103 104 105
str = & str[0];
Name of array is equivalent to address of 1st character in that array.
String Input and Output:
char str[10];
scanf(“%c”,&str[0]); // reading character
scanf(“%s”,str); // reading string , termination character is space
printf(“%c”,str[0]); // printing character
printf(“%s”,str); // printing string
void gets(string name) and void puts(string name) are two library functions available
for reading and writing string respectively.
Example:
char str[10];
gets(str); //reading string , termination character is null character i.e. ‘\0’
puts(str); // writing or printing string.
Array of Strings:
Table of strings is called as array of strings.
Example:
Char name[3][10]; //Two dimensional array of strings.
name is an array of 3 strings , each containing 10 characters. The total memory required for
name is 30 bytes.
Examples:
1. Write a program to accept a string and print it.
Solution:-
#include<stdio.h>
#include<conio.h>
void main()
{
char s[80];
clrscr();
printf(“\n Enter a string “);
gets(s);
printf(“\nEntered string is = “);
puts(s);
}
2. Write a program to accept a string and print its length using string.h.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int len;
char str[80];
clrscr();
printf(“\n Enter a string “);
gets(str);
len = strlen(str);
printf(“\nLength of string is = %d“,len);
}
3. Write a program to accept a string and print its length without using string.h.
#include<stdio.h>
#include<conio.h>