SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
Ramesh.B & Ravi Kishore.Ch Page 1
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: program0
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.
String Literals
A string literal or known as string constant is a sequence of characters enclosed in double quotes.
Ex : “Hello World”
Ramesh.B & Ravi Kishore.Ch Page 2
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.
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.
Ramesh.B & Ravi Kishore.Ch Page 3
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 he 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
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.
Ramesh.B & Ravi Kishore.Ch Page 4
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 = %sn 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()
{
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.
Ramesh.B & Ravi Kishore.Ch Page 5
/* 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(“%sn”,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”;
days[3] = “Wednesday”;
days[4] = “Thursday”;
days[5] = “Friday”;
days[6] = “Saturday”;
printf(“Week days : n”);
for(i=0; i<7; i++)
printf(“%sn”,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
Ramesh.B & Ravi Kishore.Ch Page 6
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
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.
Ramesh.B & Ravi Kishore.Ch Page 7
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
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
Ramesh.B & Ravi Kishore.Ch Page 8
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>
#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
Ramesh.B & Ravi Kishore.Ch Page 9
Length Controlled String Concatenation
The function declaration for length controlled string concatenation is as follows
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
char* strchr(const char* string, int ch);
char* strrchr(const char* string, int ch);
Ramesh.B & Ravi Kishore.Ch Page 10
/* 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
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;
Ramesh.B & Ravi Kishore.Ch Page 11
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 = %sn",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);
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
Ramesh.B & Ravi Kishore.Ch Page 12
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)
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]);
Ramesh.B & Ravi Kishore.Ch Page 13
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;
}
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 textn");
gets(text);
ccount=strlen(text);
printf("Number of Characters are..%dn",ccount);
for(i=0;i<=ccount;i++)
{
if(text[i]==' ')
wcount++;
if(text[i]=='n.')
lcount++;
}
printf("Number of words are..%dn",wcount+1);
printf("Number of Lines are..%dn",lcount+1);
getch();
Ramesh.B & Ravi Kishore.Ch Page 14
}
Output :
Enter any text: Ramu is a good boy.
Number of Characters are..17
Number of Words are ..4
Number of Lines are..1
8./* Program to print 2’s complement of a given binary number*/
#include<stdio.h>
#include<string.h>
char bin[50],c[50];
void comp(int,int);
void main()
{
int i,j,len;
printf("Enter a binary number");
scanf(“%s”,bin);
len=strlen(bin);
for(i=len-1,j=0; bin[i]!=’1’; i--,j++)
{
c[j]=bin[i];
}
comp(i,j);
printf(“2s complement is %s”,c);
}
void comp(int m, int n)
{
int i,j;
c[n]=’1’;
for(i=m-1,j=n+1; i>=0; i--,j++)
{
if(bin[i]==’0’)
c[j]=’1’;
if(bin[i]==’1’)
c[j]=’0’;
}
}
Output
Enter a binary number : 1101111
2s complement is 001001
-o0o-

Weitere ähnliche Inhalte

Was ist angesagt?

C programming session 05
C programming session 05C programming session 05
C programming session 05Dushmanta Nath
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of CSuchit Patel
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++K Durga Prasad
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Dushmanta Nath
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiSowmya Jyothi
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_outputAnil Dutt
 
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdfSTRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic Manzoor ALam
 
C programming session 09
C programming session 09C programming session 09
C programming session 09Dushmanta Nath
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1tanmaymodi4
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in Carshpreetkaur07
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in CShivanshuVerma11
 

Was ist angesagt? (20)

C programming session 05
C programming session 05C programming session 05
C programming session 05
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_output
 
Unit 8. Pointers
Unit 8. PointersUnit 8. Pointers
Unit 8. Pointers
 
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdfSTRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
C programming session 09
C programming session 09C programming session 09
C programming session 09
 
C pointer
C pointerC pointer
C pointer
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
 
Data type in c
Data type in cData type in c
Data type in c
 
Pointers In C
Pointers In CPointers In C
Pointers In C
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
 

Ähnlich wie Strings-Computer programming

Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptxJawadTanvir
 
Chapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdfChapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdfKirubelWondwoson1
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programmingmikeymanjiro2090
 
C UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYC UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYRajeshkumar Reddy
 
Strings in c
Strings in cStrings in c
Strings in cvampugani
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotesSowri Rajan
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesPrabu U
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9Vince Vo
 
C programming basic concepts of mahi.pptx
C programming basic concepts of mahi.pptxC programming basic concepts of mahi.pptx
C programming basic concepts of mahi.pptxKorbanMaheshwari
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string libraryMomenMostafa
 

Ähnlich wie Strings-Computer programming (20)

String notes
String notesString notes
String notes
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Lecture 05 2017
Lecture 05 2017Lecture 05 2017
Lecture 05 2017
 
Chapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdfChapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdf
 
pps unit 3.pptx
pps unit 3.pptxpps unit 3.pptx
pps unit 3.pptx
 
Strings
StringsStrings
Strings
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
 
Team 1
Team 1Team 1
Team 1
 
C UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYC UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDY
 
Strings in c
Strings in cStrings in c
Strings in c
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
Array &strings
Array &stringsArray &strings
Array &strings
 
Datatypes in c
Datatypes in cDatatypes in c
Datatypes in c
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
 
VHDL- data types
VHDL- data typesVHDL- data types
VHDL- data types
 
C programming basic concepts of mahi.pptx
C programming basic concepts of mahi.pptxC programming basic concepts of mahi.pptx
C programming basic concepts of mahi.pptx
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
 
Ds lec 14 filing in c++
Ds lec 14 filing in c++Ds lec 14 filing in c++
Ds lec 14 filing in c++
 

Mehr von nmahi96

Matlab lab manual
Matlab lab manualMatlab lab manual
Matlab lab manualnmahi96
 
Heat transfer(HT) lab manual
Heat transfer(HT) lab manualHeat transfer(HT) lab manual
Heat transfer(HT) lab manualnmahi96
 
Personal Survival Techniques(PST)
Personal Survival Techniques(PST)Personal Survival Techniques(PST)
Personal Survival Techniques(PST)nmahi96
 
Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)nmahi96
 
Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)nmahi96
 
Elementary First Aid(EFA)
Elementary First Aid(EFA)Elementary First Aid(EFA)
Elementary First Aid(EFA)nmahi96
 
INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)nmahi96
 
Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999nmahi96
 
Graduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questionsGraduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questionsnmahi96
 
FEA intro patran_nastran
FEA intro patran_nastranFEA intro patran_nastran
FEA intro patran_nastrannmahi96
 
Ansys beam problem
Ansys beam problemAnsys beam problem
Ansys beam problemnmahi96
 
Screw thread measurement
Screw thread measurementScrew thread measurement
Screw thread measurementnmahi96
 
Optical measuring instruments
Optical measuring instrumentsOptical measuring instruments
Optical measuring instrumentsnmahi96
 
Tolerance and Fits
Tolerance and FitsTolerance and Fits
Tolerance and Fitsnmahi96
 
Ignition system
Ignition systemIgnition system
Ignition systemnmahi96
 
Clutch system
Clutch systemClutch system
Clutch systemnmahi96
 
Braking system
Braking systemBraking system
Braking systemnmahi96
 

Mehr von nmahi96 (20)

Matlab lab manual
Matlab lab manualMatlab lab manual
Matlab lab manual
 
Heat transfer(HT) lab manual
Heat transfer(HT) lab manualHeat transfer(HT) lab manual
Heat transfer(HT) lab manual
 
STSDSD
STSDSDSTSDSD
STSDSD
 
Personal Survival Techniques(PST)
Personal Survival Techniques(PST)Personal Survival Techniques(PST)
Personal Survival Techniques(PST)
 
Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)Personal Survival and Social Responsibilities(PSSR)
Personal Survival and Social Responsibilities(PSSR)
 
Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)Fire prevention and Fire Fighting(FPFF)
Fire prevention and Fire Fighting(FPFF)
 
Elementary First Aid(EFA)
Elementary First Aid(EFA)Elementary First Aid(EFA)
Elementary First Aid(EFA)
 
INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)INERT GAS SYSTEM(IG)
INERT GAS SYSTEM(IG)
 
Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999Practical Marine Electrical Knowledge 2ed 1999
Practical Marine Electrical Knowledge 2ed 1999
 
Sensors
SensorsSensors
Sensors
 
Graduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questionsGraduate marine engineering(GME)important questions
Graduate marine engineering(GME)important questions
 
FEA intro patran_nastran
FEA intro patran_nastranFEA intro patran_nastran
FEA intro patran_nastran
 
Ansys beam problem
Ansys beam problemAnsys beam problem
Ansys beam problem
 
Ansys
Ansys Ansys
Ansys
 
Screw thread measurement
Screw thread measurementScrew thread measurement
Screw thread measurement
 
Optical measuring instruments
Optical measuring instrumentsOptical measuring instruments
Optical measuring instruments
 
Tolerance and Fits
Tolerance and FitsTolerance and Fits
Tolerance and Fits
 
Ignition system
Ignition systemIgnition system
Ignition system
 
Clutch system
Clutch systemClutch system
Clutch system
 
Braking system
Braking systemBraking system
Braking system
 

Kürzlich hochgeladen

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptMsecMca
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 

Kürzlich hochgeladen (20)

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 

Strings-Computer programming

  • 1. Ramesh.B & Ravi Kishore.Ch Page 1 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: program0 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. String Literals A string literal or known as string constant is a sequence of characters enclosed in double quotes. Ex : “Hello World”
  • 2. Ramesh.B & Ravi Kishore.Ch Page 2 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. 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.
  • 3. Ramesh.B & Ravi Kishore.Ch Page 3 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 he 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 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.
  • 4. Ramesh.B & Ravi Kishore.Ch Page 4 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 = %sn 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() { 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.
  • 5. Ramesh.B & Ravi Kishore.Ch Page 5 /* 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(“%sn”,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”; days[3] = “Wednesday”; days[4] = “Thursday”; days[5] = “Friday”; days[6] = “Saturday”; printf(“Week days : n”); for(i=0; i<7; i++) printf(“%sn”,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
  • 6. Ramesh.B & Ravi Kishore.Ch Page 6 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 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.
  • 7. Ramesh.B & Ravi Kishore.Ch Page 7 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 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
  • 8. Ramesh.B & Ravi Kishore.Ch Page 8 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> #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
  • 9. Ramesh.B & Ravi Kishore.Ch Page 9 Length Controlled String Concatenation The function declaration for length controlled string concatenation is as follows 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 char* strchr(const char* string, int ch); char* strrchr(const char* string, int ch);
  • 10. Ramesh.B & Ravi Kishore.Ch Page 10 /* 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 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;
  • 11. Ramesh.B & Ravi Kishore.Ch Page 11 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 = %sn",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); 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
  • 12. Ramesh.B & Ravi Kishore.Ch Page 12 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) 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]);
  • 13. Ramesh.B & Ravi Kishore.Ch Page 13 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; } 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 textn"); gets(text); ccount=strlen(text); printf("Number of Characters are..%dn",ccount); for(i=0;i<=ccount;i++) { if(text[i]==' ') wcount++; if(text[i]=='n.') lcount++; } printf("Number of words are..%dn",wcount+1); printf("Number of Lines are..%dn",lcount+1); getch();
  • 14. Ramesh.B & Ravi Kishore.Ch Page 14 } Output : Enter any text: Ramu is a good boy. Number of Characters are..17 Number of Words are ..4 Number of Lines are..1 8./* Program to print 2’s complement of a given binary number*/ #include<stdio.h> #include<string.h> char bin[50],c[50]; void comp(int,int); void main() { int i,j,len; printf("Enter a binary number"); scanf(“%s”,bin); len=strlen(bin); for(i=len-1,j=0; bin[i]!=’1’; i--,j++) { c[j]=bin[i]; } comp(i,j); printf(“2s complement is %s”,c); } void comp(int m, int n) { int i,j; c[n]=’1’; for(i=m-1,j=n+1; i>=0; i--,j++) { if(bin[i]==’0’) c[j]=’1’; if(bin[i]==’1’) c[j]=’0’; } } Output Enter a binary number : 1101111 2s complement is 001001 -o0o-