0% found this document useful (0 votes)
8 views15 pages

Strings AR16

Download as doc, pdf, or txt
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 15

Strings

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.

Fixed Length Strings


If the size of string variable is known, then it is called fixed-length string. A problem associated with storing
variable data in a fixed length data structure is how to tell data from the non data. It can be done by non data
characters like spaces, at the end of data. A character selected to represent a non-data value cannot be used as
data.

Variable Length Strings


If the size of string variable is variable, then it is called variable length strings. They can expand and contract
to accommodate the data. This flexibility does not come without a cost. There must be some way to tell when we get
to the end of the data. Two techniques used are

Length controlled Strings


Length controlled strings add a count that specifies the number of characters in the string. This string is then
used by string manipulation functions to determine the actual length of the data.
Ex :7program

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.

Referencing String Literals


A string literal is stored in memory. It has an address. Thus, we can refer to a string literal by using pointers.
The literal, since it is an array of characters, is itself a pointer constant to th first element of string. Generally when we
use it, we are referring to the entire string. It is possible, to refer only one of the characters in the string.
Ex:void main()
{
printf(“%s”, “Hello”);
printf(“\n%c”, “Hello”[1]);
}
Output
Hello
e

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’ }

Strings and Assignment Operator


Since, the string is an array, the name of the a string is a pointer constant. So therefore a string cannot be
used as the left operand of the assignment operator.
Ex: char str1[6] = “Hello”;
char str2[6];
str1 = str2; //compile error

Reading and Writing Strings


A string can be read and written. C provides several string functions for input and output.

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

/* Program to demonstrate puts/fputs usage */


#include<stdio.h>
void main()
{

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 Manipulation Functions


C has provided a rich set of string functions. These functions make program easier and provides the
opportunity to make them more efficient when the operation is supported by hardware instructions.
The traditional string functions have a prefix of str. The basic format is
int str…. (parameters)
The string character functions are found in the string library (string.h).

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

/* Program to find the length of string using strlen() function */


#include<string.h>
#include<stdio.h>
void main()
{
char ch[20];
int len=0;
printf("Enter a string :");
scanf("%s",ch);
len= strlen(ch);
printf("Length = %d",len);
getch();
}
Output
Enter a string : hai
Length = 3

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

Length Controlled String Copy


The function contains a parameter that specifies the maximum number of characters that can be moved at a
time. The function declaration is as follows
char* strncpy(char* toStr, const char* fromStr, int size);
In this function, size specifies the maximum number of characters that can be moved. Actually, the operation is a little
more complex.
 If the size of from string is equal to or greater than size, then size characters are moved.
 If the from string is smaller than size, the entire string is copied and then null characters are inserted into the
destination string until exactly size characters have been copied.
 If the sending string is longer than size, the copy stops after size bytes have been copied.
The string number copy functions do not insert a delimiter if the from string is longer than size.
/* Program to copy string from source to destination using strncpy() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
printf("Enter a string :");
scanf("%s",str1);
strncpy(str2,str1,5);
printf("Copied String = %s",str2);
}
Output
Enter a string : Good Morning
Copied String = Good

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.

Basic String Compare


The function declared for the string compare function is as below
int strcmp(const char* str1, const char* str2);
While the string compare functions returns integer values, we can code a logical expression that returns true or false
by using the compare function and relational operators.

/* Program to compare two strings using strcmp() function*/


#include<stdio.h>
#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=strcmp(str1,str2);
if(i==0)
printf("Strings are Equal");
else
printf("Strings are not Equal");
}
Output
Enter first string : good
Enter second string : GOOD
Strings are not Equal

Length Controlled String Compare


The string number compare function, strncmp tests two strings for a specified maximum number of characters
(size). The function declaration is as follows
int strncmp(const char* str1, const char* str2, int size);
In this function, size specifies the maximum number of characters to be compared in the first string. The strncmp
compare logic is the same in strcmp except for the length limit.
/* Program to compare two strings using strncmp() function*/
#include<stdio.h>

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.

/* Program to concatenate two strings using strcat() function*/


#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf("Enter first string :");
scanf("%s",str1);
printf("Enter second string :");
scanf("%s",str2);
strcat(str1,str2);
printf("Concatenated String = %s",str1);
getch();
}
Output
Enter first string : Data
Enter second string : Structures
Concatenated String : DataStructures

Length Controlled String Concatenation


The function declaration for length controlled string concatenation is as follows

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.

/* Program to concatenate two strings using strcat() function*/


#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf("Enter first string :");
scanf("%s",str1);
printf("Enter second string :");
scanf("%s",str2);
strncat(str1,str2,6);
printf("Concatenated String = %s",str1);
getch();
}
Output
Enter first string : Data
Enter second string : Structures
Concatenated String : DataStruct
String Reverse
The reverse of a string can be done by using the function strrev. The function declaration is as follows
char* strrev(char* string);
/* Program to reverse a string using strrev() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20];
clrscr();
printf("Enter a string :");
scanf("%s",str1);
strrev(str1);
printf("Reverse String = %s",str1);
getch();
}
Output
Enter a string : world
Reverse String = dlrow

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

/* Program to search character using strrchr() 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 11

Search for a Substring


We can locate a substring from the beginning of main string. There is no function to locate a sub string starting
at the rear. The function declaration of strstr is as follows
char* strstr(const char* string, const char* sub_string);
/* Program to search substring using strstr() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[40]=”American International”, str2[10]=”nation”;
char *ptr;
clrscr();
ptr = strstr(str1,str2);
printf(“The substring is %s”,ptr);
}
Output
The substring is national

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

2./*Program to copy a string to another without using string functions */


#include<stdio.h>
#include<string.h>
void main()
{
char str1[20], str2[20];
int i=0;
clrscr();
printf("Enter first string :");
scanf("%s",str1);
while(str1[i]!='\0')
{
str2[i]=str1[i];
i++;
}
printf("Given String = %s\n",str1);
printf("Copied String = %s",str2);
getch();
}
Output
Enter first string : Program
Given String : Program
Copied String : Program

3./*Program to concatenate two strings without using string functions */


#include<stdio.h>
#include<string.h>
void main()
{
char str1[20], str2[20];
int i=0,j=0,len=0;
printf("Enter first string :");
scanf("%s",str1);

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

4./*Program to reverse a string without using string functions */


#include<stdio.h>
#include<string.h>
void main()
{
char str1[20], str2[20];
int i=0,j=0,len=0;
clrscr();
printf("Enter a string :");
scanf("%s",str1);

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

5. /*Program to check give string is palindrome or not*/


#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
int i;
clrscr();
printf("Enter a string :");
scanf("%s",str1);
strcpy(str2,str1);
strrev(str1);
i=strcmp(str1,str2);
if(i==0)

Page 13
printf("Palindrome");
else
printf("Not Palindrome");
getch();
}
Output
Enter a string : MADAM
Palindrome

6. /*Program to convert roman number to decimal number*/


#include<stdio.h>
#include<string.h>
int getValue(char);
void main()
{
char str[20];
int i,m,n,len=0,num=0;
clrscr();
printf("Enter a roman number : ");
scanf("%s",str);
len=strlen(str);
for(i=0; i<len; i++)
{
m=getValue(str[i]);
n=getValue(str[i+1]);
if(m==0 || n==0)
{
printf(“Not a roman number”);
num=0;
break;
}
if(m<n)
num = num – m;
else
num = num + m;
}
printf(“Decimal number = %d”,num);
getch();
}
int getValue(char ch)
{
int value=0;
switch(ch)
{
case ‘I’ : value=1;
break;
case ‘V’ : value=5;
break;
case ‘X’ : value=10;
break;
case ‘L’ : value=50;
break;
case ‘C’ : value=100;
break;
case ‘D’ : value=500;
break;
case ‘M’ : value=1000;
break;

Page 14
}
retrun value;
}
Output
Enter a roman number : LIV
Decimal Number = 54

7. /*Program to count number of characters, words and lines in a given text*/


#include<stdio.h>
#include<string.h>
void main()
{
char text[20];
int i,ccount=0,wcount=1,lcount=0;
clrscr();
printf("Enter any text\n");
gets(text);
ccount=strlen(text);
printf("Number of Characters are..%d\n",ccount);
for(i=0;i<=ccount;i++)
{
if(text[i]==' ')
wcount++;
if(text[i]=='\n.')
lcount++;
}
printf("Number of words are..%d\n",wcount+1);
printf("Number of Lines are..%d\n",lcount+1);
getch();
}
Output :
Enter any text: Ramu is a good boy.
Number of Characters are..17
Number of Words are ..4
Number of Lines are..1

Page 15

You might also like