0% found this document useful (0 votes)
9 views28 pages

Understanding Character Arrays in C

The document provides an overview of character arrays (strings) in C programming, detailing their definition, declaration, initialization, and common operations such as reading, writing, copying, and comparing strings. It also covers built-in string handling functions from the string.h library, including strlen, strcpy, strcmp, and strcat, along with examples demonstrating their usage. Additionally, the document includes examples of string manipulation techniques such as counting characters and words, reversing strings, and checking for palindromes.

Uploaded by

kaustubh.kuniyal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views28 pages

Understanding Character Arrays in C

The document provides an overview of character arrays (strings) in C programming, detailing their definition, declaration, initialization, and common operations such as reading, writing, copying, and comparing strings. It also covers built-in string handling functions from the string.h library, including strlen, strcpy, strcmp, and strcat, along with examples demonstrating their usage. Additionally, the document includes examples of string manipulation techniques such as counting characters and words, reversing strings, and checking for palindromes.

Uploaded by

kaustubh.kuniyal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

C H A R A C T E R A R R AYS

(STRINGS)
Strings
Definition
 A string is an array of characters.
Declaration and initialization
char string_name[size];
For example, consider the following array:
char name [20]; is an array that can store up to 20 elements of type
char.

The common operations performed on strings are


Reading and writing strings
Combining strings together
Copying one string to another
Comparing strings to another
Extracting a portion of a string ..etc.
Strings
The character sequences "Hello" and "Merry Christmas" represented in an
array name respectively are shown as follows :

To initialize an array of characters with some predetermined


sequence of characters one can initialize like any other array:

char myWord[ ] = { 'H', 'e', 'l', 'l', 'o', '\0' };


Initialization of null-terminated character sequences
 Arrays of char elements have an additional methods to initialize their
values: Using string literals
 “Manipal ” is a constant string literal.
For example,
char result[14] =“Manipal”;
 Double quoted (") strings are literal constants whose type is in fact a
null-terminated array of characters. So string literals enclosed between
double quotes always have a null character ('\0') automatically appended
at the end.
char myWord [ ] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char myWord [ ] = "Hello";
 In both cases, the array of characters myword is declared with a size of
6 elements of type char:
Example
#include <stdio.h>
int main() {
char question[ ] = "Please, enter your first name: ";
char greeting[ ] = "Hello, ";
char yourname [ 80];
printf(“%s”,question);
scanf(“%s”, yourname;)
printf(“%s, %s\n”,greetings , yourname );
return 0;
}
Example

#include <stdio.h>
int main()
{
const int MAX = 80; //max characters in string
char str[MAX]; //string variable str
printf( “Enter a string: \n”);
scanf(“%s”,str); //put string in str
printf(“%s”,str); //display string from str
return 0;
}
Reading Embedded Blanks
To read everything that you enter from the keyboard until the
ENTER key is pressed (including space).
Syntax: gets(string) ;
#include <stdio.h>
#include<string.h>
int main()
{
char str[80]; //string variable str
printf(“\nEnter a string: ”);
gets(str); //put string in str or use gets(str)
printf(“ the string is \n“);
puts(str);
return 0;
}
Count the number of characters in a string

#include <stdio.h>
int main()
{
char sent[100];
int i=0, count=0;
printf("enter sentence \n“);
gets(sent);
puts(sent);
while(sent[i]!='\0')
{
count++;
i++;
}
printf(“%d \n no of characters = “, count);
return 0;
}
Count the number of words in a sentence

#include <stdio.h> while(sent[i]!='\0')


{
int main()
if (sent[i]==' '&& sent[i+1]!=' ')
{ count++;
i++;
const int MAX = 100;
}
char sent[MAX]; printf(“n %d n no. of words = " ,count);
return 0;
int i=0,count=1;
}
printf("enter sentence \n“);
gets(sent);
printf("\n“);
Reading multiple lines: Example
#include <stdio.h>
int main()
{
const int MAX = 2000; //max
char str[MAX]; //string
printf("\nEnter a string:\n“);
gets(str);
printf("You entered:\n“);
printf(“%s”,str);
return 0;
}

The function will continue to accept characters until enter key is pressed.
Library functions: String Handling functions (built-in)
• Used to manipulate a given string.
• These functions are part of string.h header file.
strlen ()
 gives the length of the string. E.g. strlen(string)
strcpy ()
 copies one string to other. E.g. strcpy(Dstr1,
Sstr2)
strcmp ()
 compares the two strings. E.g. strcmp(str1, str2)
strcat ()
Concatinate the two strings. E.g. strcat(str1,
str2)
Library function: strlen()
• String length can be obtained by using the following function
n=strlen(string);
• The argument may be a string constant.
Eg: printf(“%d”,strlen(“Manipal”)); prints out 7.
int main()
{
char str1[ ] = “Manipal Institute of Technology”;
char str2[80]; //empty string
int n=strlen(str1);
for(int j=0 ; j<n; j++) //copy strlen characters
{str2[j] = str1[j]; } // from str1 to str2
str2[j] = ‘\0’; //insert NULL at end
printf(“%s”,str2); //display str2
return 0;
}
Extracting a character from a string
#include <stdio.h> D E L H I

#include<string.h>
int main() sent[0] sent[1] sent[2] sent[3] sent[4]
{ Enter sentence
Delhi
char sent[100]; 5 (length of string sent)
int len; I
printf("enter sentence \n“); D
gets(sent);
len=strlen(sent);
printf(“%d\n”,len);
printf(“%c\n”,sent[len-1]);
printf(“%c\n”,sent[0]); }
To encrypt and decrypt a string
#include <stdio.h> for(i=0;sent[i]!=‘\0’;i++)

#include<string.h> sent[i]=sent[i]+1;
int main() printf(“ the encrypted string is \n”);
{ puts(sent);
const int MAX = 100;
for(i=0;sent[i]!=‘\0’;i++)
char sent[MAX];
sent[i]=sent[i]-1;
int len,I;
printf(“ the decrypted string is \n”);
printf("enter sentence \n“);
puts(sent);
gets(sent);
}
Library function: strcpy()
Copying a String the EASY WAY using
strcpy(destination, source)
destination may be a character array variable or a string constant.
e.g., strcpy(city, ``DELHI”);
will assign the string “DELHI” to the string variable city.

#include <stdio.h>
int main()
{
char str1[ ] = “Tiger, tiger, burning bright\n”
“In the forests of the night”;
const int MAX = 80; //size of str2 buffer
char str2[MAX]; //empty string
strcpy(str2, str1); //copy str1 to str2
printf(“%s”,str2);//display str2
}
Library function: strcmp()
 The strcmp function compares two strings identified by the
arguments and has a value 0 if they are equal.
 If they are not, it has the numeric difference between the first non
matching characters in the strings.
strcmp(string1, string2);
string1 and string2 may be string variables or string constants.
e.g., strcmp(“their”, ”there”); will return a value of –9 which is the
numeric difference between ASCII “i” and ASCII “r”. That is, “i” minus
“r” with respect to ASCII code is –9.
If the value is negative, string1 is alphabetically above string2.
Library function: strcat()
The strcat function joins two strings together.

It takes the following form:


strcat(string1, string2);
string1 and string2 are character arrays.
When the function strcat is excuted, string2 is
appended to string1.
 It does so by removing the null character at the end
of string1 and placing string2 from there.
The string at string2 remains unchanged.
Concatenation of 2 strings
#include <stdio.h>
#include <string.h>
int main()
{ char s1[40], s2[50];
printf("\nEnter the first string“);
gets(s1);
printf("\nEnter the second string“);
gets(s2);
strcat(s1, s2);
printf("\nConcatenated string is“);
printf(“%s”,s1);
return 0; }
Check whether a string is Palindrome or not

int main() for(i=0;i<n/2;i++)


{ {
char str[30]; if(str[i]!=str[n-i-1])
int i, j, n, flag=1; { flag=0;
printf("\nEnter the string:“); break; }
gets(str); }
//find the string length if(flag==1)
n=strlen(str); printf("\nIts a Palindrome“);
else
printf("\nNot a Palindrome“);
return 0;
}
Reversing a string

int main() for(i=0;i<n/2;i++)


{ {
char str[70]; temp=str[i];
char temp; str[i]=str[n-i-1];
int i, n=0; str[n-i-1]=temp;
printf("\nEnter the string:“); }
gets(str); printf("\nReversed string is:“);
//find the string length puts(str);
n=strlen(str); return 0;
}
Change all lower case letters into uppercase in a
sentence

int main() for(i=0;i<n;i++)


{ {
char string[30]; if(string[i]>=97 && string[i]<=122)
int i,n=0; string[i]=string[i]-32;
printf("\nEnter the string“); }
gets(string);
puts(string);
for(i=0;string[i]!='\0';i++) getch();
n++; return 0;
}
Strings Bubble Sort

for(i=0;i<no-1;i++)
for(j=i+1;j<no;j++)
int main()
{
{
if(strcmp(string[i],string[j
char string[30][30],temp[30];
])>0)
int no, i, j; {
cout<<"\nEnter the no of strings:";
strcpy(temp,string[i]);
cin>>no;
cout<<"\nEnter the strings:"; strcpy(string[i],string[j]);

for(i=0;i<no; i++) strcpy(string[j],temp);


gets(string[i]); }
}

cout<<"\nThe sorted
array is:";
for(i=0;i<no;i++)
Finding Substring in Main String

Main string: cc aa bb
Sub-String : aa

Enter main string:- cc aa bb


Enter sub-string : aa
Substring aa is found at
positions 3
Finding Substring in Main String
int main()
{
char str1[80],str2[80];
int i,j,len=0;

cout<<"Enter the main string :\n";


gets(str1);

cout<<"Enter sub string :\n";


gets(str2);

//finding length of substring


for(i=0;str2[i]!='\0'; i++)
len++;
Finding Substring in Main String

for(i=0,j=0; str1[i]!='\0‘ && str2[j]!='\0'; i++)


if(str1[i]==str2[j])
j++;
else
j=0;

if(j==len)
cout<<"Substring\t"<<str2<< "\tfound at position "<<i-j+1;
else
cout<<"Substring not found";

}
Tutorials on Simple Operations on String

• Write a simple C program to retrieve first word from a sentence.

• Write a C program to remove blank space from the string

• Write a C program to count the number of vowels and consonants in a


given string.
Sorting n names in alphabetical order
int main()
for(i=0;i<no-1;i++)
{
for(j=i+1;j<no;j++)
char string[30]
{
[30],temp[30];
int no, i, j;
if(strcmp(string[i],string[
printf("\nEnter the no of
)>0)
strings:";
{
scanf(“%d”,&no);
printf("\nEnter the
strcpy(temp,string[i]);
strings:“);
for(i=0;i<no; i++)
strcpy(string[i],string[j]);
gets(string[i]);
strcpy(string[j],temp);
}
}
Extra problem: Finding Substring in Main String
Main string: cc aa bb aa aa
Sub-String : aa

Enter main string:- cc aa bb aa aa


int main() Enter sub-string : aa
{
Substring is present 3 times at
int i=0,j=0,k=0,count=0;
positions 4 10 13
int l=0,k1=0,cn[10],c=0;
char a[80],b[80];

cout<<"\nEnter main string:-\n";


gets(a);
cout<<"\nEnter sub-string:-\n";
gets(b);
l=strlen(b); //length of substring

You might also like