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

Module 4.1 - Strings

Uploaded by

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

Module 4.1 - Strings

Uploaded by

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

Module IV - Strings

INTRODUCTION
A string is a null-terminated character array. This means that after the last character, a null
character (‘\0’) is stored to signify the end of the character array.
Declaration:
The general form of declaring a string is
char string_name[size];
E.g. char name[20], city[20];
Initializing:
 E.g.1: char city[9] = “New York”;
 E.g. 2: char city[9] = {‘N’,’e’,’w’,'',’Y’,’o’,’r’,’k’,’\0’};
Null character ‘\0’ inserted by compiler in e.g.1.
Specify array size considering ‘\0’ also.
 E.g.: char city[9] = “New York”;

 char str[9] = “Good”; // Valid initialization

 char str1[9] ;
str1 = “Good”; // Error: Not allowed to assignment like this in C

READING STRINGS

If we declare string by writing


char str[100];
Then str can be read from the user by using three ways:
1. use scanf function
2. using gets() function
3. using getchar()function repeatedly
 The string can be read using scanf() by writing
scanf(“%s”, str);
 The string can be read by writing
gets(str);
gets() takes the starting address of the string which will hold the input. The string inputted
using gets() is automatically terminated with a null character.
 The string can also be read by calling the getchar() repeatedly to read a sequence of single
characters (unless a terminating character is entered) and simultaneously storing it in a
character array.
i=0;
getchar(ch);
while(ch != '*’)
{
str[i] = ch;
i++;
getchar(ch);
}
str[i] = '\0';

WRITING STRINGS

The string can be displayed on screen using three ways


1. use printf() function
2. using puts() function
3. using putchar()function repeatedly
 The string can be displayed using printf() by writing
printf(“%s”, str);
 The string can be displayed by writing
puts(str);
 The string can also be written by calling the putchar() repeatedly to print a sequence of single
characters
i=0;
while(str[i] != '\0*)
{
putchar(str[i]);
i++;
}
OPERATIONS ON STRINGS WITHOUT USING BUILT-IN FUNCTIONS

1. Finding the length of a string.


Approach: Length is initialized to 0. Then a loop is run checking every character in the array from
start. For every character other than ‘\0’ length is incremented by one. Loop stops when the first
‘\0’ is encountered. So we get the count of how many characters other than ‘\0’ are found. That is
the length of the string.
// Finding length of a string
#include <stdio.h>
int main()
{
char s[20],i,length;
printf("Enter first string: ");
gets(s);
length = 0;
while(s[length] != '\0')
{
length++;
}
printf("Length = %d", length);
return 0;
}
2. Copy String without using built-in function strcpy()
Approach: We have two arrays. Source array stores the string entered by the user. Destination
array is the array to which this string is to be copied. Run a loop to take each character from the
source array and put it in the corresponding location of the destination array. The loop stops when
‘\0’ is found in the source array. Once out of the loop add a ‘\0’ character at the end of characters
stored in the destination array to mark the end of the string.
Program:
#include<stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
gets(s1);
for(i =0; s1[i]!='\0';i++)
{
s2[i]= s1[i];
}
s2[i]='\0'; // Adding null character for the new copy.
printf("String s2: %s", s2);
return 0;
}
3. Concatenate Two Strings Without Using built-in function strcat()
Approach: Find the index of ‘\0’ character in the destination array by running a loop.
for(i =0; s1[i]!='\0';++i);
Now variable i has the index value of ‘\0’ in string s1. In a new loop take each character from
source array and put in to destination array s1 at index starting from i,i+1....etc. until all characters
of source string s2 are copied. At last put a ‘\0’ at the end of all characters in destination array s1.
Program:
#include<stdio.h>
int main()
{
char s1[100], s2[100], i, j;
printf("Enter first string: ");
gets(s1);
printf("Enter second string: ");
scanf("%s", s2);
// calculate the length of string s1 and store it in i
for(i =0; s1[i]!='\0';i++);
// Now ‘i' has the length of s1(same as the index of ‘\0’).
// s[i] has '\0' of string s1
// Copy characters from string s2 to s1[i] onwards
for(j =0; s2[j]!='\0';j++,i++)
{
s1[i]= s2[j];
}
s1[i]='\0';
printf("After concatenation: %s", s1);
return0;
}
4. Reversing a string
Approach: First length of string is found using the previous method. In a loop, swap 1st and last
characters, then 2nd and second last character & so...on. This process is repeated and we get the
string in reverse order.
// Reversing string without additional array
#include <stdio.h>
int main()
{
char str[20],temp;
int len,i;
printf("Enter the word\n");
gets(str);
for(len = 0;str[len]!='\0';len++);
l=len-1;
printf("strlen is %d\n",len);
for(i =0;i<l;i++,l--)
{
temp = str[i];
str[i] = str[l];
str[l] = temp;
}
printf("Reversed string is: %s\n",str);
return 0;
}

5. Comparing two strings


Comparing two strings
 If both are same result==> 0
 If 1st precedes 2nd in alphabetical order, result ==> -1
 If 2nd precedes 1st in alphabetical order, result ==> 1
#include <stdio.h>
int main()
{
char s1[100], s2[100], i, j;
printf("Enter first string: ");
gets(s1);
printf("Enter second string: ");
gets(s2);
for(i = 0; s1[i]!='\0' && s2[i]!='\0'; i++)
{
if(s1[i] < s2[i])
{
// s1 should come first alphabetically
printf("-1") ;
return 0;
}
if(s1[i] > s2[i] )
{
// s2 should come first alphabetically
printf("1") ;
return 0;
}
} // end of loop
if(s1[i] == '\0' && s2[i] == '\0') //if both strings are over
{
//Both strings are equal(same)
printf("0") ;
}
else if(s1[i] == '\0') // If Only s1 is over
{
printf("-1") ; // s1 should come first alphabetically
}
else if(s2[i] == '\0')// If only s2 is over
{
printf("1") ; // s2 should come first alphabetically
}
return 0;
}
O/p:
1. Enter first string: abcd
Enter second string: abcd
0
2. Enter first string: abCd
Enter second string: abcd
-1
3. Enter first string: abcd
Enter second string: abCd
1
4. Enter first string: abcd
Enter second string: abcdef
-1
5. Enter first string: abcdef
Enter second string: abcd
1

OPERATIONS ON STRINGS WITH USING BUILT-IN FUNCTIONS

Following library functions coming as part of C for string handling.


 strcat() Concatenates two strings.
 strcmp() Compares two strings.
 strcpy() Copies one string to another.
 strlen() Finds length of string.
 strrev() reverse a string

1. strlen( ) : Returns the length of a string.


length = number of characters in the string
Usage: len = strlen(string);
E.g.
char str[15] = "Hello";
int n= strlen(str); // n ==> 5
 Null character (\0) not considered for length calculation
program
void main()
{
char str[15] = "Hello World";
int len;
len = strlen(str);
printf("Length = %d",len);
}
Output:
Length = 11

2. strcpy( ) : Copy string2 to string1(second to first string)


Usage: strcpy(string1,string2);
 String1 should be large enough to contain string2
Program
char str1[15];
char str2[15] = "Hello World";
strcpy(str1,str2); // str1 "Hello World"

String handling functions: strcpy

#include<stdio.h>
#include<string.h>
void main()
{
char str1[15];
char str2[15] = "Hello World";
strcpy(str1,str2);
printf("Copied string:");
puts(str1);
}
3. strcat( ): Concatenates two strings.
Usage: strcat(str1,str2);
Str2 is appended at the end of str1. The combined string is stored in str1. Make sure str1 is large
enough to contain concatenation of str1 and str2.
// strcat
#include<stdio.h>
#include<string.h>
void main()
{
char str1[15] = "Hello";
char str2[6] = "World";
strcat(str1,str2);
puts(str1);
}
o/p: HelloWorld

Concatenates user entered strings: strcat


#include<stdio.h>
#include<string.h>
void main()
{
char str1[20], str2[20];
printf("Enter string 1:");
gets(str1);
printf("Enter string 2:");
gets(str2);
strcat(str1,str2);
printf("Concatenated string:");
puts(str1);
}
o/p:
Enter string 1:hello
Enter string 2:world
Concatenated string:helloworld

4. strrev(): reverse a string


Usage: strrev(string);
E.g.
char str[15] = "Hello";
strrev(str); // str "olleH"

String handling functions: strrev


#include<stdio.h>
#include<string.h>
int main()
{
char str[20];
printf("Enter a string: ");
gets(str);
strrev(str);
printf("Reversed string is: %s",str);
return 0;
}
o/p:
Enter a string: hello

5. strcmp(): Compares two strings.


Usage: strcmp(string1,string2);
 Return values:
0 if both strings are same
< 0 if string1 precedes string2 alphabetically (-1 mostly)
> 0 if string2 precedes string1 alphabetically (1 mostly)
Example for strcmp

char str1[15] = "ABCD";


char str2[10] = "abcd";
int r = strcmp(str1,str2); // r = -1
r = strcmp("abcd","abcd"); // r=0
r = strcmp("abcd","abCd"); // r=1
r = strcmp("abcd","abfd"); // r=-1
r = strcmp("abfd","abcd"); // r=1
r = strcmp("ABCD","abcd"); // r=-1

ARRAYS OF STRINGS
Now suppose that there are 20 students in a class and we need a string that stores names of all the
20 students. Here, we need a string of strings or an array of strings.
An array of string is declared as:
char names[20][30];
Where,
The first index represents the number of strings and the second index specifies the length of
individual string. So here, we allocate space for 20 names where each name can be maximum of 30
characters long.
General Syntax:
<data_type> <array_name> [row_size][column_size];

Let us see the memory representation of an array of strings. If we have an array declared as,
char name[5][10] = {“Ram”, “Mohan”, “Shyam”, “Hari”, “Gopal”};
WRITE A PROGRAM TO READ AND PRINT THE NAMES OF N STUDENTS OF A
CLASS
#include <stdio.h>
int main()
{
char names[5][10];
int i, n;
printf(“\n Enter the number of students : “);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
printf(“\n Enter the name of %dth student : “, i+1);
gets(names[i]);
}
for(i=0;i<n;i++)
{
puts(names[i]);
}
return 0;
}

Write functions to implement string operations such as compare, concatenate, and


find string length. Use the parameter passing techniques.
#include<stdio.h>
int string_length(char *a[50])
{
int i=0,l=0;
while(a[i]!='\0')
{
l++;
i++;
}
return l;
}
void con_strings(char *a[50],char *b[50])
{
int i,j,k=0,length;
l=string_length(a);
for(i=0;b[i]!='\0';i++)
{
a[l]=b[i];
}
a[l]='\0';
printf(“After concatenation %s”,a);
}
int comp_strings(char *s1[50],char *s2[50])
{
int i,j=0,k=0;
for(i = 0; s1[i]!='\0' && s2[i]!='\0'; i++)
{
if(s1[i] < s2[i])
{
// s1 should come first alphabetically
printf("-1") ;
return 0;
}
if(s1[i] > s2[i] )
{
// s2 should come first alphabetically
printf("1") ;
return 0;
}
}
if(s1[i] == '\0' && s2[i] == '\0') //if both strings are over
{
//Both strings are equal(same)
printf("0") ;
}
else if(s1[i] == '\0') // If Only s1 is over
{
printf("-1") ; // s1 should come first alphabetically
}
else if(s2[i] == '\0')// If only s2 is over
{
printf("1") ; // s2 should come first alphabetically
}
return 0;
}
int main()
{
char s1[20];
int i;
char s2[20];
scanf("%s",s1);
scanf("%s",s2);
length= string_length(s1)
printf("Length of the first string is %d",length);
length= string_length(s1)
printf("Length of the second string is %d",length);
comp_strings(s1,s2);
con_strings(s1,s2);
return 0;
}

Palindrome (Without Library functions)


#include <stdio.h>
#include <string.h>
int main()
{
char string[20];
int flag = 0, i = 0, length;
printf("Enter the word\n");
scanf("%s", string);
// Finding length of string without library
length =0;
while(string[length]!='\0')
{
length++;
}
for(i=0;i < length/2 ;i++)
{
if(string[i] != string[length-i-1])
{
flag = 1;
printf("%s is not a palindrome", string);
break;
}
}
if (flag==0)
{
printf("%s is a palindrome", string);
}
return 0;
}
Palindrome (Using library functions)
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
char string[20];
printf("Enter the word\n");
scanf("%s",string);
// Create a copy of string
strcpy(str,string);
int len,i;
char temp;
len = strlen(str);
for(i = 0;i<len;i++,len--)
{
temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
if(strcmp(string,str) == 0)
{
printf("%s is a palindrome\n", string);
}
else
{
printf("%s is not a palindrome\n", string);
}
return 0;
}

You might also like