Strings AR16
Strings AR16
Strings AR16
String Concepts
A string is a series of characters treated as a unit. Virtually all string implementations treat string as a variable-
length piece of data.
Delimited Strings
Delimited strings identify the end of string by using delimiter. The major disadvantage of the delimiter is that it
eliminates one character from being used for data. The most common delimiter is the ASCII null character (\0). This is
the techniques used in C.
Ex: program\0
C Strings
A C string is a variable-length array of characters that is delimited by the null character.
Storing Strings
In C, a sting is stored in an array of characters. It is terminated by null character(\0). The difference between
one character stored in memory and one character string stored in memory is, the character requires only one
memory location where as the string requires two : one for data and other for delimiter.
String Delimiter
The implementation of string is logical but not physical. The physical structure is array in which the stored.
Since string is a variable length structure, logical end of data within physical structure must be identified.
The null character is used as an end-of-string marker. It is the sentinel used by the standard string functions.
Page 1
String Literals
A string literal or known as string constant is a sequence of characters enclosed in double quotes.
Ex : “Hello World”
When string literals are used in the program, C automatically creates an array of characters initializes it to a null-
delimited string and stores it, remembering is address. It does all this because we use the double quotes that
immediately identify the data as a string value.
Declaring Strings
C has no string type. As it is defined as sequence of characters, it is stored using character array. The storage
structure, must be one byte larger than the maximum data size because there is a delimiter at the end.
Ex : A string of 8 characters length can be declared as
char str[9];
String definition defines memory for a string when it is declared as an array in local memory. We can also declare a
string a pointer. When we declare the pointer, memory is allocated for the pointer, no memory is allocated for the
string itself.
Ex : char *pStr;
Initializing Strings
A string can be initialized by assigning a value to it when it is defined.
Ex : char str[9] = “Good day”;
Since a sting is stored in an array of characters, we do not need to indicate the size of the array if we initialize.
Ex : char str[] = “C Program”;
In the above case, the compiler will create an array of 10 bytes and initializes it with “C Program” and a null character.
If we now tried to store “Programming” in str array it is not possible as the length is not sufficient. So, a string
variable is initialized with a longest value.
C provides two more ways to initialize strings. A common method is to assign a string literal to a character pointer.
Page 2
Ex : char *pStr = “Hello World”;
We can also initialize a string as an array of characters. This method is not used too often because it is so tedious to
code.
Ex: char str[12] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘\0’ }
Character Input/Output
1. getchar()
The function reads character type from the standard input. It reads one character at a time till the user
presses the enter key.
2. putchar()
This function prints one character on the screen at a time which is read by the standard input.
/* Program to accept characters through keyboard using Character I/O function */
#include <stdio.h>
void main()
{
char ch;
printf("Enter a character :");
ch = getchar();
putchar(ch);
}
Output
Enter a character : M
M
String Input/Output
In addition to the formatted string functions, C has two sets of string functions that read and write strings
without reformatting any data. These functions convert text-file lines to strings and strings to text-file lines.
C provides two parallel set of functions, one for characters and one for wide characters. They are virtually
identical except for the type.
Line to String
Page 3
The gets and fgets functions take a line from the input stream and make a null terminated string out of it. They
are therefore sometimes called line-to-string input functions. The function declarations for get string are shown below
char* gets (char* strPtr);
char* fgets(char* strPtr, int size, FILE* sp);
The source of data for the gets is standard input; the source of data for fgets can be a file or standard input.
Both accept a string pointer and return the same pointer if the input is successful.
If any input problems occur, such as detecting end-of-file before reading any data, they return NULL.
If no data were read the input area is unchanged.
If an error occurs after some data have been read, the contents of the read-in area cannot be determined.
Since no size is specified in gets, it reads data until it finds a new line or until the end of file. If new line character is
read, it is discarded and replaced with a null character.
The fgets function requires two additional parameters: one specifying the array size that is available to receive the
data and other a stream. It can be used with the keyboard by specifying the stdin. In addition to new-line and end of
file, the reading with stop when size-1 characters have been read.
/* Program to determine the usage of gets and fgets*/
#include<stdio.h>
void main()
{
char name[20], add[50];
printf(“Enter your name :”);
gets(name);
printf(“Enter your address :”);
fgets(add, sizeof(add), stdin);
printf(“ Name = %s\n Address = %s”, name,add);
}
Output
Enter your name : Sukruth
Enter your address : Hyderabad
Name = Sukruth
Address = Hyderabad
String to Line
The puts/fputs functions take a null-terminated string from memory and write it to a file or the keyboard. All
change the string to a line. The null character is replaced with a newline is puts; it is dropped in fputs. Because puts is
writing to the standard output unit, usually a display, this is entirely logical. On the other hand, fputs is assumed to be
writing to a file where newlines are not necessarily required.
The declarations for these functions are
int puts( const char* strPtr);
int fputs( const char* strPtr, FILE* sp);
Page 4
char str[]= “Good Morning”;
char name[20];
puts(“Enter your name :”);
gets(str);
puts(str);
fputs(str, stdout);
fputs(“\n”,stdout);
fputs(str+5, stdout);
}
Output
Enter your name : Raja
Raja
Good Morning
Morning
Array of Strings
Array of strings can be defined as the two dimensional character array. If we want to arrange few strings in an
array it can be done by declaring two dimensional character array
char names[7][20];
The above declarations says that there are 7 rows with 20 columns means 7 strings with each string a maximum of 20
characters.
/* Program to demonstrate the array of strings */
void main()
{
char names[5][20];
int i;
printf(“Enter 5 names :”);
for(i=0; i<5; i++)
scanf(“%s”,names[i]);
printf(“Given names :\n”);
for(i=0; i<5; i++)
printf(“%s\n”,names[i]);
}
Output
Enter 5 names : Kiran Kumar Karthik Kamal Kapil
Given names :
Kiran
Kumar
Karthik
Kamal
Kapil
It is much easier and more efficient to create a array of string using pointers. Each pointer points to individual
string. In this way each string is independent, but at the same time they are grouped together through an array.
char* days[7];
/*Program to demonstrate the array of strings */
void main()
{
char* days[7];
int i;
days[0] = “Sunday”;
days[1] = “Monday”;
days[2] = “Tuesday”;
Page 5
days[3] = “Wednesday”;
days[4] = “Thursday”;
days[5] = “Friday”;
days[6] = “Saturday”;
printf(“Week days : \n”);
for(i=0; i<7; i++)
printf(“%s\n”,days[i]);
}
Output
Week days :
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
String Length
The string length function strlen returns the length of a string specified as the number of characters in the
string excluding the null character. If the string is empty it returns zero. The function declaration is as follows
int strlen(const char* string);
String Copy
C has two copy functions. The first strcpy copies the contents of one string to another. The second strncpy
copies the contents of one string to another but it sets a maximum number of characters that can be moved.
Basic String Copy
Page 6
The string copy function, strcpy, copies the contents of the from string, including the null character, to the
string. The function declaration is shown below
char* strcpy(char* toStr, const char* fromStr);
If fromStr is longer than toStr, the data in memory after toStr is destroyed. So the destination string array should be
large enough to hold the sending string.
/* Program to copy string from source to destination using strcpy() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
printf("Enter a string :");
scanf("%s",str1);
strcpy(str2,str1);
printf("Copied String = %s",str2);
}
Output
Enter a string : C Program
Copied String = C Program
String Compare
Page 7
C has two string compare functions. The first strcmp compares two string until unequal characters are found
or until the end of the strings reached. The second strncmp compares until unequal characters are found, a specified
number of characters have been tested or until the end of a string is reached.
Both functions return an integer to indicate the results of the compare.
If the two stings are equal, the return value is zero.
If the first parameter is less than the second parameter, the return value is less than zero i.e. negative value.
If the first parameter is greater than the second parameter, the return value is greater than zero i.e. positive
value.
Page 8
#include<string.h>
void main()
{
char str1[20],str2[20];
int i;
clrscr();
printf("Enter first string :");
scanf("%s",str1);
printf("Enter second string :");
scanf("%s",str2);
i=strncmp(str1,str2,3);
if(i==0)
printf("Strings are Equal");
else
printf("Strings are not Equal");
}
Output
Enter first string : Good Morning
Enter second string : Good Afternoon
Strings are Equal
String Concatenate
The string concatenate functions append one string to the end of another. They return the address pointers to
the destination string. The size of the destination string array is assumed to be large enough to hold the resulting
string. If it isn’t the data at the end of the string array are destroyed.
Basic String Concatenation
The function declaration is as follows
char* strcat(char* str1, const char* str2);
The function copies str2 to the end of str1, beginning with str1’s delimiter. That is ,the delimiter is replaced with the
first character of str2. The delimiter from str2 is copied to the resulting string to ensure that a valid string results.
Page 9
char* strncat(char* str1, const char* str2, int size);
If the length of string2 is less than size, then the call works the same as the basic string concatenation.
If the length of string is greater than size, then only the number of characters specified by size are copied and
a null character is appended at the end.
If the value of size is zero or less than zero, then both strings are treated as null, and no characters are
moved. The variable string1 is unchanged.
Character to String
Two string functions search for a character in a string. The first function is called strin character strchr, it
searches for the first occurrence of character from the beginning of the string. The second string rear character strrchr,
searches for the first occurrence beginning at the rear and working toward the front.
The function declarations for these functions are shown below
Page 10
char* strchr(const char* string, int ch);
char* strrchr(const char* string, int ch);
/* Program to search character using strchr() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str[20]=”This is string”;
char *ptr, c = ‘i’;
clrscr();
ptr = strchr(ptr,c);
if(ptr)
printf(“The character %c is found in position %d”,c, ptr-string);
else
printf(“The character %c is not found”,c);
getch();
}
Output
The character i is found in position 2
Page 11
Sample Programs
1./*Program to calculate length of string without using string functions */
#include<stdio.h>
#include<string.h>
void main()
{
char name[50];
int i=0;
clrscr();
printf("Enter your name :");
scanf("%s",name);
while(name[i]!='\0')
{
i++;
}
printf("Length = %d",i);
getch();
}
Output
Enter your name : Sanjay
Length = 6
Page 12
printf("Enter second string :");
scanf("%s",str2);
while(str1[i++]!='\0')
{
len++;
}
for(i=len,j=0; str2[j]!='\0'; i++,j++)
{
str1[i] = str2[j];
}
printf("Concatenated String = %s",str1);
getch();
}
Output
Enter two strings : Hello
World
Concatenated String : HelloWorld
while(str1[i++] !='\0')
{
len++;
}
for(i=len-1,j=0; i>=0; i--,j++)
{
str2[j] = str1[i];
}
str2[j]='\0';
printf("Reverse String = %s",str2);
getch();
}
Output
Enter a string : program
Reverse String = margorp
Page 13
printf("Palindrome");
else
printf("Not Palindrome");
getch();
}
Output
Enter a string : MADAM
Palindrome
Page 14
}
retrun value;
}
Output
Enter a roman number : LIV
Decimal Number = 54
Page 15