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

Unit 3 Strings

Uploaded by

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

Unit 3 Strings

Uploaded by

JUSTIN RAJ S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

CSE101R01 –

Problem Solving & Programming in C

Unit 3 - Strings
Introduction
• The names of various people, cities, companies, addresses, lots of other official and personal
details are sequence of characters either alphabet or alphanumeric mostly and rarely pure
integers.
• In that case, these are treated as array of characters and most of the applications require
support to read, write, copy, search, concatenate etc.
• In C language, array of characters have been treated as a complete entity named as string
and many special library functions have been provided to process these strings.
• A string is an array of characters terminated a special symbol named as null
character(represented as ‘\0’). Hence the null character is also called as string-termination
character. It is used to identify the length of a string.
• All characters, individual digits, all punctuation/special symbols and all operator symbols can
be stored as characters, as each of them has a separate ASCII code.
• A String consists of n characters can be logically shown as illustrated below.
Defining a String
• String is declared in the same manner as an array, except that its data type is
specified as character.

storage_class char var_name [size];

• Where storage_class refers to the storage class of the string, it is optional.


• var_name is the user-chosen name for the string
• Size is positive integer value, which indicates number of characters including
the null
character
• Exampls:
char name[50];
static char address[100];
Null Character
• Most important in string handling is null character. It is used to terminate a string and to
compute the actual length of a string
• As compared to other arrays, the string size is not stored in a separate variable.
• String reading and writing also done without using the size variable.
• The string definition specifies the maximum length. For example, 50 incase of name variable
given in example. But the length of input string will be usually less than 50, as illustrated
below.
Initialization of Strings
• Strings can be initialized at the time of definition in the same way as done for the other
arrays. It can also be initialized using double quotes. Both of these methods are described
below
char str[30] = “Hello World”;
char str[30] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’};

• In both cases, the null character will be automatically get appended in the end.
• Both of these initializations will result into storage as shown below.
• Strings (i.e., character arrays) are handled somewhat differently
• When a string constant is assigned to a character array as a part of the array definition, the
array size specification is usually omitted.
• The proper array size will be assigned automatically.
• This will include a provision for the null character ‘\0’, which is automatically added at the
end of every string
• Consider the following 2 character array definitions. Each includes the initial assignment of
the string constant "RED". However, the first array is defined as a three-element array,
whereas the size of the second array is unspecified.
char color[3] = "RED";
char color[ ] = "RED";
• The results of these initial assignments are not the same because of the null character, ‘\0’,
which is automatically added at the end of the second string.
• Thus, the elements of the first array are
color[0] = 'R'
color[1] = 'E'
color[2] = 'D'
• whereas the elements of the second array are
color[0] = 'R '
color[1] = 'E'
color[2] = 'D'
color[3] = '\0'
• The first form is incorrect, since the null character ‘\0’ is not included in the array.
• The array definition could also have been written as
char color[4] = "RED"
Reading and Writing a String
• A string can be read and written using a single scanf and printf functions using %s and no
loop is needed, which is compulsory for reading and writing of arrays of other data types.

#include<stdio.h>

int main() {
char str[100];
printf(“\n Enter a string of maximum 100 characters : “);
scanf(“ %s “,str);
printf(“\n The entered string is : %s”, str);
return 0;
}
• When the program is executed its output will look like:
• Input / Output 1:
Enter a string of maximum 99 characters : Programming
The entered string is : Programming

• Input / Output 2:
Enter a string of maximum 99 characters : New Delhi
The entered string is : New
• The scanf() function reads a string from the key board till a whitespace character(blank or tab
or newline) is encountered.
• After the reading is complete, the null character is appended automatically at the next
position inside the array. In first case null character is appended at str[11]. During printing,
the printf function keeps on printing the individual characters of the array till the null
character is not reached.
• The scanf function with %s is used to read strings not consisting of spaces. So, if we give the
input as New Delhi, only New gets stored in the array. So the null character is appended at
str[3].
• To read string consisting of blank characters as well, the gets() functions is the easiest way. To
use gets() and puts() functions, string.h header file must be included.
• Following program is an example to read and print string with spaces.

#include<stdio.h>
#include<string.h>
int main() {
char str[100];
printf(“\n Enter a string of maximum 100 characters : “);
gets(str);
puts(“\n The entered string is :”);
puts(str);
return 0;
}
• Another alternate to read a string consisting of alphabets, digits, blanks, punctuation symbols
is,
scanf(“%[^\n]”, str);
Which reads all characters till the enter key (that is ‘\n’) is not pressed.

#include<stdio.h>

int main() {
char str[100];
printf(“\n Enter a string of maximum 100 characters : “);
scanf(“%[^\n]”,str);
printf(“\n The entered string is : %s”, str);
return 0;
}
• Strings can be read or written character by character also. This method is similar to reading
the elements of an array of integers, with a difference that the end of the input is detected
by pressing the “Enter key”.
• This method requires the use of scanf with %c or getchar functions.
• Example: Using scanf function:
#include<stdio.h>
int main() {
char str[100];
int i = 0;
do {
scanf(“%c”, &str[i]);
i = i + 1;
}while(str[i -1] != ‘\n’);
str [i]= ‘\0’;
printf(“\n The entered string is : %c”, str);
return 0;
}
• Example: Using getchar function:
#include<stdio.h>
int main() {
char str[100];
int i = 0;
do {
str[i] = getchar();
i = i + 1;
}while(str[i -1] != ‘\n’);
str [i]= ‘\0’;
printf(“\n The entered string is : %s”, str);
return 0;
}
• Example: Displaying string character by character using printf
#include<stdio.h>
int main() {
char str[100] = “Welcome to SASTRA”;
int i = 0;
while(str[i ] != ‘\0’) {
printf(“%c”, str[i]);
i = i + 1;
}
return 0;
}
• Example: Displaying string character by character using putchar functions

#include<stdio.h>
int main() {
char str[100] = “Welcome to SASTRA”;
int i = 0;
while(str[i ] != ‘\0’) {
putchar(str[i]);
i = i + 1;
}
return 0;
}
Processing Strings
• The strings can be processed either by using some predefined functions with the help of the
string.h header file or by processing all characters individually.
• Many useful predefined functions provided in string.h header file.
• Some commonly used predefined functions are,

– int strlen(string_var) - To compute the length of the string, not counting


null character
– strcpy(dst_string, src_string) - To copy a source string into destination string
– int strcmp(str1, str2) - To compare str1 with str2
– strcat(dst_string, src_string) - To append copy of the source string at the end of
destination string
• The following program demonstrates the use of if(strcmp(str1,str3)==0){
all these functions printf("\n Both strings are equal...");
}else if(strcmp(str1,str3)<0){
#include<stdio.h> printf("\n First string is less than second
#include<string.h> string...");
int main(){ }else{
int len; printf("\n First string is greater than second
char str1[100], str2[100], str3[100]; string...");
char tmpstr[100]; }
printf("\n Enter a string : ");
gets(str1); printf("\n Enter a string to append at the right
side of string1 : ");
len = strlen(str1);
gets(tmpstr);
printf("\n Length of given string is : %d", len);
strcat(str1, tmpstr);
strcpy(str2, str1);
printf("\n First string, after concatenation :
printf("\n Given string is %s, and copied string is
%s",str1);
%s", str1,str2);
printf("\n Enter a string to compare : "); return 0;
gets(str3); }
• The execution of the previous program will give the following result.
• Program to check two strings are equal or int main()
not using user defined functions {
char str1[80], str2[80];
#include <stdio.h> printf("Enter first string: ");
#include<string.h> gets(str1);
// String compare, equal or not, ignore case
// this function will return 0 if str1 != str2 printf("Enter second string: ");
// and return 1 if str1 == str2 gets(str2);
// string length user defined function if(isequal_ignorecase(str1,str2)==1){
// string lowercase user defined function printf("\n Equal");
}else{
int findstrlength(char str[]); printf("\n Not equal");
void tolowercase(char str[]); }
int isequal_ignorecase(char str1[], char str2[]); return 0;
}
int findstrlength(char str[]) int isequal_ignorecase(char str1[], char str2[])
{ {
int i=0,len=0; int len1, len2;
for(i=0;str[i]!='\0';i++){ int i, equal=1;
len++; len1=findstrlength(str1);
} len2=findstrlength(str2);
return len; if(len1==len2){
} tolowercase(str1);
tolowercase(str2);
void tolowercase(char str[]) for(i=0;i<len1;i++){
{ if(str1[i]!=str2[i]){
int i; equal=0;
for(i=0;str[i]!='\0';i++){ break;
if(str[i]>=65 && str[i]<=90){ }
str[i] = str[i]+32; }
} }else{
} equal=1;
} }
return equal;
}
#include <stdio.h>
// String copy, without using predefined void stringcopy(char dest[], char src[])
// functions {
void stringcopy(char dest[], char src[]); int i=0;
int main() for(i=0;src[i]!='\0';i++){
{ dest[i] = src[i];
char str1[80], str2[80]; }
printf("Enter first string: "); }
gets(str1);

stringcopy(str2, str1);

printf("\n First String : %s", str1);


printf("\n Second String : %s", str2);
return 0;
}
• Program to count number of vowels in given case 'i':
input string. case 'I':
#include<stdio.h> case 'o':
#include<string.h> case 'O':
case 'u':
int main(){ case 'U':
char text[100]; vowelcount++;
int i, len, vowelcount = 0; }
printf("\n Enter a line of text : "); }
scanf("%[^\n]",text); printf("\n Total vowels in given input line is :
len = strlen(text); %d",vowelcount);
for(i=0;i<len;i++){ return 0;
switch(text[i]){ }
case 'a':
case 'A':
case 'e':
case 'E':
#include <stdio.h> r = stringcomp(str1, str2);
if(r==0){
// String compare, without using predefined printf("\n Both the strings are equal...");
// functions }else if(r==-1){
// this function will return 0, if str1 == str2 printf("\n First string is less than second
// return -1 if str1 < str2 string...");
// return 1 if str1 > str2 }else{
int stringcomp(char str1[], char str2[]); printf("\n First string is greater than second
string...");
int stringlen(char str[]);
}
return 0;
int main()
}
{
char str1[80], str2[80];
int r=0;
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
int stringcomp(char str1[], char str2[]) if(count==len1 && count==len2){
{ return 0;
int i,j,count=0; }
int len1=0, len2=0, len; }
len1 = stringlen(str1);
len2 = stringlen(str2);
len = len1<len2?len1:len2; int stringlen(char str[])
for(i=0; i<len; i++){ {
if(str1[i] == str2[i]){ int i, len=0;
count++; for(i=0;str[i]!='\0';i++){
}else if(str1[i]<str2[i]){ len++;
return -1; }
}else{ return len;
return 1; }
}
}
#include <stdio.h> printf("Enter string to concatenate : ");
#include<string.h> gets(src);
// String concat, without using predefined printf("\n 1. Left Concat \n 2. Right Concat");
functions printf("\n Enter your choice : ");
// this program contains two functions scanf("%d",&choice);
// rightconcat function will append src string at
end if(choice==1){
// of dst string leftconcat(dest, src);
// leftconcat function will append src string at printf("\n After concat : %s",dest);
// begining of dst string }else if(choice==2){
rightconcat(dest, src);
void rightconcat(char dst[], char src[]); printf("\n After concat : %s",dest);
void leftconcat(char dst[], char src[]); }else{
int main() printf("\n Invalid choice...");
{ }
char dest[100], src[100]; return 0;
int choice; }
printf("\n\nEnter first string: ");
gets(dest);
void rightconcat(char dest[], char src[]) void leftconcat(char dest[], char src[])
{ {
int i,j; int i,j;
int len=0; int len1=0, len2=0;
len = strlen(dest); len1 = strlen(dest);
for(i=len,j=0;src[j]!='\0';i++,j++){ len2 = strlen(src);
dest[i] = src[j]; for(i=len1;i>=0;i--){
} dest[i+len2]=dest[i];
dest[i] = '\0'; }
} for(i=0;src[i]!='\0';i++){
dest[i]=src[i];
}
dest[len1+len2] = '\0';
}
Character Arithmetic
• Characters are treated as integer type internally in most of the high level programming
languages. Hence, most of the arithmetic operations of integers are possible on characters
as well.
• We can increment, decrement, add, subtract, and even multiply two characters.
• This is because characters uses their equivalent ASCII codes internally.
• When we perform arithmetic operations on a character, it actually gets operated on the
equivalent ASCII code of that character.
• For example, ASCII code of ‘A’ is 65. When you apply increment operation on a character
variable which contains ‘A’, then its ASCII value 65 will be incremented by 66. 66 is ASCII
value for “B”. So, now the variable will have “B”.

char ch = ‘A’;
printf(“\n %c”,ch); // This statement will print A
ch ++; // This statement will increment the ASCII code of ‘A’
printf(“\n %c”, ch); // This statement will print B
• Some more examples:

char ch1, ch2, ch3;


int val;
ch1 = ‘A’;
ch2 = ch1 + 3; // ch2 becomes ‘D’
ch3 = ch1 + ch2; // ch3 gets value equal to addition of ASCII values of ‘A’ and ‘D’
ch1 ++; // ch1 becomes ‘B’
ch2 - - ; // ch2 becomes ‘C’
printf(“%d”, ‘a’); // ASCII code of ‘a’, 97 gets printed
printf(“%d”, ‘2’); // ASCII code of ‘2’, 50 gets printed
val = ch1 * ch2; // val = 66 * 67 (ASCII code of ‘A’ and ‘C’
printf(“%c”,100) // character for ASCII code 100 gets printed, that is ‘d’
• Character arithmetic is used in conversion of uppercase to lowercase and vice versa.

#include<stdio.h>
#include<string.h>
int main(){
char text[100];
int i;
printf("\n Enter a line of text : ");
scanf("%[^\n]",text);
len = strlen(text);
for(i=0;i<len;i++){
if(text[ i ] >=‘a’ && text[ i ] <=‘z’)
text[ i ] = text[ i ] + (‘A’ – ‘a’);
}
printf(“\n Upper case of given input string is : %s”, text);
}
Searching and Sorting of strings
• Sorting→ arrange the name in alphabetical order
• Searching→ pattern of characters occurs in a given
text
• Searching of substring requires finding all of the
characters of the substring are present from anu
position onwards in the main string
• Searching start from subscript ‘0’ of the main string
and checking whether all characters of the substring
are present in the same sequence from 0th position
onwards or not.
Keyword searching in a text
#include<stdio.h>
#include<string.h>
main() Output:
{ String: The programming is a systematic
char text[100], substr[30];
process.
int text_len, sub_len, i, j;
printf("Enter the main string"); Substring: pro
gets(text); Subscript: 4
printf("Enter the substring to be searched"); 32
gets(substr);
text_len = strlen(str);
sub_len = strlen(substr);
for(i=0; i<text_len-sub_len; i++)
{
for(j=0; j<sub_len; j++)
if(text[i+j]==substr[j])
continue;
else
break;
if (j==sub_len)
printf("the substring is present from %d,"i);
}
}
Sorting an array
• Store the string within a 2D character array
• Each string will be stored in a separate row within the array
• strcmp → compare two strings (accept two strings as an
argument and returns an integer value)
• Negative value→ first string precedes the second string
alphabetically
• Zero→ both are identical
• Positive value→ second string precedes the first string
• Strcpy→ copy one string to another
• Strcmpi→ compare both upper and lower letters
Sorting a set of city names in an alphabetical order
#include<stdio.h>
for(i=0; i<n; i++)
#include<string.h> {
main() for(j=i+1; j<n; j++)
{ if(strcmp(str[i], str[j])>0)
{ strcpy(s,str[i]);
char str[100][100], s[100]; strcpy(str[i],str[j]);
int i, j, n; strcpy(str[j], s);
printf("Enter number of city names:"); }}}
printf(“The sorted city names are:");
scanf(“%d”,&n); for(i=0; i<n; i++)
printf("Enter city names in any order:"); { printf(“%s”, str[i]);}}
for(i=0; i<n; i++)
{scanf(“%s”,&str[i]);
}
Other string functions
• strcpy(dest, src, n) → copy upto n char from src to dest
• strncmp(str1, str2, n)→ compare n char in str1&str2
• strncmpi(str1, str2)→ ignore case sensitive
• strlwr(str1)
• strupr(str1)
• strncat(dest, src, n)
• memcpy(dest, src, n)→ copy first n bytes of strings str1 and str2
• memcmp(dest, src, n)
• memset(str1, ch, n)
• strchr(str1, ch)
• strset(str1, ch)
• strnset(str1, ch, n)
• strrev(str1)
• strstr(str1,str2)
• i to a(val,str1,radix)
• a to i(str1)

You might also like