0% found this document useful (0 votes)
124 views

Character Array and String

This document discusses strings and character arrays in C. It explains that strings are represented as character arrays terminated by a null character. It provides examples of declaring and initializing string variables. It also covers reading and writing strings, comparing strings, concatenating strings, and built-in string handling functions.

Uploaded by

bishramoraon896
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
124 views

Character Array and String

This document discusses strings and character arrays in C. It explains that strings are represented as character arrays terminated by a null character. It provides examples of declaring and initializing string variables. It also covers reading and writing strings, comparing strings, concatenating strings, and built-in string handling functions.

Uploaded by

bishramoraon896
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Character Array and String

String

A string is a sequence of characters that is treated as a single data item. The


common operations that can be performed on character string are

 Reading and writing


 Concatenation
 String copying
 String comparison
 Extraction of a portion of string

Declaring and Initializing String Variables

C does not support string as a data type. String is represented as character type
array. It means in C, string variable is any valid C variable name declared as an
array of characters. The general syntax is char string_variable_name[size].

Example char Name[20];

When the compiler assigns a character string to a character array, it automatically


assigns a null character i.e. ‘\0’ at the end of the string. Hence the size specified
for character type array has to be one more than the number of characters in the
array.

Example char Name[5]={‘A’, ‘M’, ‘I’, ‘T’, ‘\0’};

C permits initialization of a character type array without specifying the number


of elements.

Example char Name[ ]={‘A’, ‘M’, ‘I’, ‘T’, ‘\0’};

We can also declare the size of the string larger than the string size in the
initialization.

Example char Name[15]= “AMIT”;

C Programming Page 1
Character Array and String

In the above case a character type arry of size 15 is created. The value “AMIT” is
placed in it and terminated by ‘\0’ character. The remaining elements are too
initialized by ‘\0’ character.

i.e. A M I T ‘\0’ ‘\0’‘\0’ ‘\0’‘\0’ ‘\0’‘\0’ ‘\0’‘\0’ ‘\0’ ‘\0’

The declaration and initialization part of the string cannot be segregated. It


means

char Name[20];

Name= “AMIT”;

is not allowed and will result in compile time error. Also an array name cannot be
used as an operand on the L.H.S. of an assignment operator. Hence

char Name[5]= “AMIT”;

char name[5];

name=Name; /* It is not allowed*/

Why Null character is used to terminate the string?

String is not a data type in C. In fact it is a data structure stored in an array. It


means the string which is a variable length structure is stored in a fixed length
array. The size of array is not always the size of the string and in general it is much
larger than the string stored in it. Hence the last element of the array needs not
to be the end of the string and we have to specifically specify the “end of the
string” and this is being done with the help of ‘\0’ i.e. null character.

Reading Strings Through Keyboard

C Programming Page 2
Character Array and String

Using the function scanf()

The input function scanf() is used along with the format specification “%S” to read
a string of characters.

Example char Name[20];

scanf(“%S”, Name);

Limitation

The major limitation with the function scanf() while reading string of characters
is that as soon as the first white space is encountered, it terminates the reading
process i.e. its input. A white space includes

 Blank space
 Tab space
 Carriage return
 Form feeds
 New line etc.

If in the above example the keyboard input is AMIT KUMAR SINGH, then only the
string “AMIT” will be read into the array Name as the blank space after the string
“AMIT” is encountered, it will terminate the reading of the string.

Now look at the following example

char Name1[20], Name2[20];

scanf(“%S %S”, Name1,Name2);

If the keyboard input is AMIT KUMAR, then the string “AMIT” will be assigned to
Name1 and “KUMAR” will be assigned to Name2.

C Programming Page 3
Character Array and String

Reading A Line of Text

As we know C supports a format specification called edit set conversion code


%[…]. This can be used to read a line containing a variety of characters.

Example

char Line[100];

scanf(“%[^\n]”, Line);

printf(“%S”, Line);

Using the function getchar()

The function getchar() is used to read a single character from keyboard. The
recursive use of the function getchar() allows us to read successive single
characters from input and place them into a character type array.

Example

char ch;

char Name[20];

for(int i=0;i<20,i++)

ch=getchar();

Name[i]=ch;

OR

char Name[20];

C Programming Page 4
Character Array and String

for(int i=0;i<20,i++)

Name[i]=getchar();

Using the function gets()

The function gets() is used to read a string of text containing white spaces. The
method is defined in the header file “stdio.h”, that has to be included. It accepts
one parameter which is of string type.

Example

char Name[20];

gets(Name);

it will read string of characters into character type array until it encounters a new
line character. Once the new line character is encountered, it appends a null
character is encountered, it appends a null character at the end to mark the “end
of the string”.

Displaying String

Using the function printf()

The output function printf() is used along with the format specification “%S” to
write a string of characters onto the monitor.

Example

char Name[20];

C Programming Page 5
Character Array and String

Scanf(“%S”, Name);

printf(“%S”,Name);

We can also specify the precision with which the array will be displayed.

Example

printf(“%15.7 S”, Name);

First 7 characters are to be printed in a field width of 15 columns with right


justification.

printf(“-%15.7 S”, Name)

First 7 characters are to be printed in a field width of 15 columns with left


justification.

Using the function putchar()

The function putchar() is used to output the values of character type variable i.e.
the output of single character onto monitor. The recursive use of the function
putchar() allow us to write successive single characters onto the output screen.
The function putchar() requires one character type parameter.

Example

char Name[20];

for(int i=0;i<20;i++)

Name[i]=getchar();

for(i=0;i<20;i++)

C Programming Page 6
Character Array and String

putchar(Name[i]);

Using The Function puts()

The function puts() is used to print the string values. The header file “stdio.h” has
to be included. It accepts one parameter which is of string type. The general
syntax is puts(Name).

Where Name is the string type parameter/argument passed to the method puts().
It writes the contents of the string variable Name and moves the cursor to the
beginning of the next line on the screen.

Example

char Name[20];

gets(Name);

puts(Name);

Arithmetic Operations on Characters

C allows us to manipulate characters the same way we do with the numbers.


Whenever a character constant or variable is used in an expression, it is
automatically converted into an integer value by the system. This integer value
depends on the local character set of the system.

 To write a character in its integer representation.


If the machine uses ASCII representation then
char ch= ‘A’;
printf(“%d\n”, ch);/*will produce the output 65*/

C Programming Page 7
Character Array and String

printf(“%d\n”, ch+1);/*will produce the output 66*/

 To test whether the character contained in the variable is an uppercase


char ch;
printf(“enter any character”);
ch=getchar();
if(ch= ‘A’ && ch= ‘Z’)
printf(“Uppercase”);
else
printf(“Lowercase”);
 To convert a character digit to its equivalent integer value
int a=65-‘0’;
=65-48;
=17
 To convert a string of digits into their integer values
char Number[5]= “2014”;
int year=atoi(Number);

Putting Strings Together

String concatenation is the process of combining two strings together. We just


cannot assign one string to another directly. We cannot join two strings together
by simple arithmetic.

Example

char Name1[10]= “Hello”;

char Name2[10]= “World”;

char Name[20]= Name1+ Name2 is an invalid C statement.

The characters from Name1 and Name2 should be copied into Name one after
the other. The size of 3rd array Name has to be large enough to hold total numbers
of characters from the strings Name1 and Name2.

Example

C Programming Page 8
Character Array and String

char name1[10]= “Hello”;

char Name2[10]= “World”;

char Name3[50];

for(int i=0; Name1[i]!= ‘\0’;i++)

Name3[i]=Name1[i];

Name3[i+1= “ ”;

for(j=0; Name2[j]!= “\0”; j++)

Name3[i+j+1]=Name2[j];

puts(Name3);

Comparison of Two Strings

C does not permit the direct comparison between two strings. It means

if(str1==str2)

OR

if(str1== “XYZ”) is invalid C statement.

C Programming Page 9
Character Array and String

Hence it is necessary to compare two strings character by character. The


comparison is done until there is a mismatch or one of the strings terminate into
a null character, whichever comes first.

Example

int i=0;

while(str1[i]==str2[i] && str1[i]!= ‘\0’ && str2[i]!= ‘\0’)

if(str1[i]== ‘\0’ && str2[i]== ‘\0’)

printf(“Strings are equal”);

else

printf(“Strings are unequal”);

String Handling Functions

C supports following string handling library functions

 strlen()
Determines the length of the string.
The function counts the number of characters in the string passed as
argument. The general syntax is strlen(char *).
#include<string.h>
void main()
{
char str[20];
int len;
clrscr();
printf(“enter a string”);

C Programming Page 10
Character Array and String

gets(str);
len=strlen(str);
printf(“\n The length of the string is %d”, len);
}

 strcpy()
Copies a string from the source to destination.
The function copies the contents of one string to the other. Two strings are
passed as argument to it. The contents of second argument (source) is
copied into first argument (destination). The general syntax is strcpy(char
*destination, char *source).
#include<string.h>
void main()
{
char str1[20], str2[20];
chrscr();
printf(“enter a string”);
gets(str1);
strcpy(str2,str1);
puts(str2);
}

 strncpy()
Copies characters of a string to another string up to the specified length.
The function strncpy() is very much similar to the function strcpy() but the
difference is it copies specified length of characters from second argument
to first argument. The general syntax is (char *destination, char *source,
int n).
#include<string.h>
void main()
{
char str1[20], str2[20];
chrscr();
printf(“enter a string”);
gets(str1);

C Programming Page 11
Character Array and String

strcpy(str2,str1,10);
puts(str2);
}

 strcmp()
Compare characters of two strings. The function is case sensitive.
The function strcmp() is used to compare two strings passed arguments and
returns 0 iff they are equal , otherwise returns a non zero value. This is
being done by comparing the ascii codes of same indexed characters of
both argument strings. If the difference between the two corresponding
ascii codes is 0, the comparison continues, but as soon the difference is non
zero, the comparison stops. If the returned value <0, the string passed as
first argument is alphabetically above the string passed as second
argument otherwise the string passed as second argument is alphabetically
above the string passed as first argument. The general syntax is strcmp(
char *s1, char *s2).
#include<string.h>
void main()
{
char str1[20], str2[20];
int i;
chrscr();
printf(“enter first string”);
gets(str1);
printf(“enter second string”);
gets(str2);
i=strcmp(str2,str1);
printf(“%d”, i);
}

 stricmp()
Compares characters of two strings. The function is not case sensitive.
The function stricmp() is used to compare two strings passed arguments.
The function is non case sensitive and returns 0 or + 32 iff they are equal,
otherwise returns a non zero value. This is being done by comparing the
ascii codes of same indexed characters of both argument strings. If the

C Programming Page 12
Character Array and String

difference between the two corresponding ascii codes is 0 or +32, the


comparison continues, but as soon the difference is non zero, the
comparison stops. If the returned value <0, the string passed as first
argument is alphabetically above the string passed as second argument
otherwise the string passed as second argument is alphabetically above the
string passed as first argument. The general syntax is stricmp( char *s1, char
*s2).
#include<string.h>
void main()
{
char str1[20], str2[20];
int i;
chrscr();
printf(“enter first string”);
gets(str1);
printf(“enter second string”);
gets(str2);
i=stricmp(str2,str1);
printf(“%d”, i);
}

 strncmp()
Compares characters of two strings up to the specifies length. The function
is case sensitive.
The function strncmp() is used to compare two strings passed arguments
up to specified length, and returns 0 iff they are equal , otherwise returns
a non zero value. This is being done by comparing the ascii codes of same
indexed characters of both argument strings. If the difference between the
two corresponding ascii codes is 0, the comparison continues, but as soon
the difference is non zero, the comparison stops. If the returned value <0
(!= -32), the string passed as first argument is alphabetically above the
string passed as second argument otherwise (!= +32) the string passed as
second argument is alphabetically above the string passed as first
argument. The general syntax is strncmp( char *s1, char *s2, int n).
#include<string.h>
void main()

C Programming Page 13
Character Array and String

{
char str1[20], str2[20];
int i;
chrscr();
printf(“enter first string”);
gets(str1);
printf(“enter second string”);
gets(str2);
i=strncmp(str2,str1,5);
printf(“%d”, i);
}

 strnicmp()
Compares characters of two strings up to the specified length by ignoring
the case sensitivity.
The function strnicmp() is used to compare two strings passed arguments
up to specified length by ignoring the case sensitivity. The general syntax is
strnicmp( char *s1, char *s2, int n).
#include<string.h>
void main()
{
char str1[20], str2[20];
int i;
chrscr();
printf(“enter first string”);
gets(str1);
printf(“enter second string”);
gets(str2);
i=strnicmp(str2,str1,5);
printf(“%d”, i);
}

 strupr()
Converts lowercase characters of a string to uppercase.

 strlwr()

C Programming Page 14
Character Array and String

Converts uppercase characters of a string to lowercase.

 strdup()
Duplicates the string.
The function strdup() is used for duplicating a given string at the allocated
memory which is pointed by the pointer variable. The general syntax is char
*s2=strdup(char *s1).
#include<string.h>
void main()
{
char str1[20], str2[20];
int i;
chrscr();
printf(“enter the string”);
gets(str1);
str2=strdup(str1);
printf(“the duplicate string is:”);
puts(str2);
}

 strchr()
Determine the first occurrence of a given character in a string.
The function returns the pointer position to the first occurrence of the
character passed as second argument within the string passed as first
argument. The general syntax is strchr(char *s, char ch).
#include<string.h>
void main()
{
char str1[20], ch;
int i;
chrscr();
printf(“enter the string”);
gets(str1);
i=strchr(str1,ch);
printf(“the required position is %d:i”);
}

C Programming Page 15
Character Array and String

 Strrchar()
Determines the last occurrence of a given character in a string.
The function returns the pointer position to the last occurrence of the
character passed as second argument within the string passed as first
argument. The general syntax is strrchr(char *s, char ch).
#include<string.h>
void main()
{
char str1[20], ch;
int i;
chrscr();
printf(“enter the string”);
gets(str1);
i=strrchr(str1,ch);
printf(“the required position is %d:i”);
}

 strstr()
Determines the first occurrence of a given string in a string.
The function returns the pointer position to the first occurrence of the
string passed as second argument within the string passed as first
argument. The general syntax is strstr(char *s1, char *s2).
#include<string.h>
void main()
{
char str1[20], str2[10];
int i;
chrscr();
printf(“enter the first string”);
gets(str1);
printf(“enter the second string”);
gets(str2);
i=strstr(str1,str2);
printf(“the required position is %d:i”);
}

C Programming Page 16
Character Array and String

 strcat()
Appends source string to the destination string.
The function strcat() is used to join or concatenate two strings. The string
passed as second argument is appended to the string passed as first
argument. This is being done by removing the null character at the end of
the string passed as first argument and placing the string passed as second
argument. The general syntax is strcat(char *s1, char *s2).
#include<string.h>
void main()
{
char str1[20], str2[10];
chrscr();
printf(“enter the first string”);
gets(str1);
printf(“enter the second string”);
gets(str2);
strcat(str1,str2);
puts(str1);
}

 strncat()
Appends source string to the destination string up to specified length.
The function strncat() is used to join or concatenate two strings. The
n(passed as third argument) characters of string passed as second
argument is appended to the string passed as first argument. This is being
done by removing the null character at the end of the string passed as first
argument and placing the string passed as second argument. The general
syntax is strcat(char *s1, char *s2, int n).
#include<string.h>
void main()
{
char str1[20], str2[10];
chrscr();
printf(“enter the first string”);
gets(str1);

C Programming Page 17
Character Array and String

printf(“enter the second string”);


gets(str2);
strcat(str1,str2,5);
puts(str1);
}

 strrev()
Reverses all the characters of a string.
The function strrev() is used to reverse the string passed as argument.
#include<string.h>
void main()
{
char str1[20];
chrscr();
printf(“enter the string”);
gets(str1);
puts(“the reverse of the string is”);
puts(strrev(str1));
}

 strset()
Sets all characters of a string with a given argument or symbol.
The function strset() is used to replace every characters of the string passed
as first argument with the symbol passed as second argument. The general
syntax is strset(char *s, char symbol).
#include<string.h>
void main()
{
char str1[20];
char symbol;
chrscr();
printf(“enter the string”);
gets(str1);
printf(“enter the symbol”);
scanf(“%c”, &symbol);
puts(srtset(str1,symbol));

C Programming Page 18
Character Array and String

 strnset()
Sets specified number of characters of a given string with given argument
or symbol.
The function strset() is used to replace specified number (passed as third
argument) characters of the string passed as first argument with the
symbol passed as second argument. The general syntax is strset(char *s,
char symbol, int n).
#include<string.h>
void main()
{
char str1[20];
char symbol;
chrscr();
printf(“enter the string”);
gets(str1);
printf(“enter the symbol”);
scanf(“%c”, &symbol);
puts(srtset(str1,symbol,5));
}

 strspn()
Finds up to what length two strings are equal.
The function strspn() returns the position of the string from where source
string(passed as first argument) is not matching with destination
string(passed as second argument). The general syntax is strspn(char *s1,
char *s2).
#include<string.h>
void main()
{
char str1[20], str2[10];
int pos;
chrscr();
printf(“enter the first string”);
gets(str1);

C Programming Page 19
Character Array and String

printf(“enter the second string”);


gets(str2);
pos=strcat(str1,str2);
printf(“the required position is %d”,pos);
}

 strpbrk()
Searches the first occurrence of the character in a given string and then
displays the string starting from that character.
The function strpbrk() is used to search the first occurrence of the character
passed as second argument in the string passed as first argument and then
displays the string from that character.
#include<string.h>
void main()
{
char str1[20], ch, *str2;
chrscr();
printf(“enter the first string”);
gets(str1);
printf(“enter the character”);
gets(str2);
str2=strpbrk(str1,ch);
printf(str2);
}

String conversion functions

 double atof(const char *)


Converts the given string to double.
#include<stdlib.h>
void main()
{
double d;
d=atof(“101.12345”);

C Programming Page 20
Character Array and String

printf(“%g”, d);
}
The string “101.12345” is passed as an argument to the function atof(),
which converts string to double. The converted double value is assigned to
the double type variable d and is then displayed.

 int atoi(const char *)


Converts the given string to int.
#include<stdlib.h>
void main()
{
int d;
d=atof(“101.12345”);
printf(“%d”, d);
}
The string “101.12345” is passed as an argument to the function atoi(),
which converts string to int. The converted integer value is assigned to the
int type variable d and is then displayed.

 long atoi(const char *)


Converts the given string to long.
#include<stdlib.h>
void main()
{
long int d;
d=atof(“101.12345”);
printf(“%ld”, d);
}
The string “101.12345” is passed as an argument to the function atoi(),
which converts string to long int. The converted long integer value is
assigned to the long int type variable d and is then displayed.

 double strtod(char *, char *)


Separates char and float data from the given string.
#include<stdlib.h>
void main()

C Programming Page 21
Character Array and String

{
const char *str=”101.12345 is the value”;
char *strp;
double d;
d=strtod(str,&strp);
printf(“%g”,d);
printf(“\n%s”, strp);
}

 long strtol(char *, char *)


Seperates char and long int data from the given string.

Memory Functions

 memcpy()
copies n number of characters from one string to another.
The function memcpy() is used to copy specified number of characters from
source string (string passed as second argument) to destination string
(string passed as first argument). The number of characters is specified by
third argument. The general syntax is mewmcpy( char *s2, char *s1, int n).
void main()
{
char str1[20],str2[20];
printf(“\n Enter the string”);
gets(str1);
memcpy(str2,str1,10);
puts(str2);
}

 memove()
moves a specified range of char from one place to another.
The function memove() is used to move specified range of characters from
given location.The general syntax is memove( char *s1, char *s2, int n). the
first argument is the string, second argument is the specified range of
characters(substring) to be moves and the third argument is the desired
location,

C Programming Page 22
Character Array and String

void main()
{
char str1[20];
printf(“\n Enter the string”);
gets(str1);
memove(str1,&str1[5],10);
puts(str1);
}

 memchr()
searches for the first occurrence of the given character.
The function memchr() is used to search for the first occurrence of the
specified character within the given string. If the first occurrence of the
specified character is found, the remaining string is displayed.
void main()
{
char str[20],ch;
printf(“\n enter the string”);
gets(str);
printd(“\n enter the character to be searched”);
scanf(“%c”, &ch);
printf(memchr(str, ch,10);
}

 memcmp()
compares the contents of memory.
The function memcmp() is used to compare the specified range of two
strings and the difference between the same indexed characters in both
strings is returned.
void main()
{
char str1[20];
char str2[20];
printf(“enter first string”);
gets(str1);
printf(“\nenter second string”);

C Programming Page 23
Character Array and String

gets(str2);
printf(“%d”, memcmp(str1,str2,10);
}

C Programming Page 24

You might also like