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

MEJ-C Language 8

Uploaded by

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

MEJ-C Language 8

Uploaded by

nirajgparmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Character strings Bala Chap 8 pages 229-262

• Array of characters terminated by null character ‘\0’.


• No built-in data type for strings → uses array of characters → char
• Allows string constants and variables
“PHYSICS” “123456789”
• Internal representation of a string has a null character ( ‘\0’ ) at the end
→ physical storage required is one more than the number of characters
• Distinguish between 2 ‘2’ “2”
• Strings are generally used to manipulate text

Common operations performed on strings are


• Reading and writing
• Getting length of strings
• Combining strings together – concatenation - appending
• Copying one string to another
• Comparing strings for equality
• etc
Declaration and initialization of string variables.
• No separate data type for stings → array of characters → char ‘a’ ‘b’ ‘c’ ‘d’ ‘e’ ‘\0’
char s[6] =; “abcde”;
s[0] s[1] s[2] s[3] s[4] s[5]
• Character variables can store only one character, String variables can store any number of characters.
char subject[12] = “ELECTRONICS”;
11 character, but it has to be declared with 12 characters, to include ‘\0’ at the end.
char dept[12] = {‘E’, ’L’, ’E’, ’C’, ’T’, ’R’, ’O’, ’N’, ’I’, ’C’, ’S’, ’\0’};
char str[10] = “Hello” → ‘H’, ’e’, ‘l’, ‘l’, ‘o’, ‘\0’, ‘\0’, ‘\0’, \0’, ‘\0’ Excess locations will be filled with ‘\0’

• Initialization with lower size is illegal.


char str[3] = “good”; → compiler error
• Do not allow assignment operations on strings except in declaration.
char str1[15] = “Gujarat”, str2[15];
str2 = “abc”; not allowed
str2 = str1; not allowed
Reading a string
char str[10] ;
scanf(“%s ”, str);
• Use %s
• No & sign before string variables
• scanf() function will automatically terminates when white space is read.

• scanf(“%s”, str); Gujarat University.


Gujarat_University or GujaratUniversity
scanf(“%s %s”, str1, str2);

Writing strings:
printf(“%s”, name);
Formatted printing
%10s, %-10s, %10.4s, %*.*s, %*.3s, %10.*s
printf(“%*.*s”, i, j, name);
/*P1 Reading a line of text */
line
#include <stdio.h> a b c d \n
#include <conio.h>
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
#include <ctype.h>
main()
{ char line[10], ch ; ch i

int i = 0; a 01
--
printf("Enter the text, press ENTER key at the end : \n"); ab cd\n
do
{ ch = getchar();
line[i] = ch; /* line[i++] = ch; not [++i] */
i++;
} while(ch != '\n');
line[i-1] = '\0'; To read/ write individual character
printf("\n%s", line); • getchar(); • gets(name);
getch(); • putchar(ch); • puts(name);
}
Declaration, initialization, reading and writing
char x1[ ] = "Hello“;
char x2[ ] = {'B','y','e','\0'};
char x3[ ] = "Thank You";
char x4[20], x5[20];
scanf("%s", x4);
gets(x5);
printf("%s %10s %-10s %10.5s", x1, x2, x3, x4);
puts(w5);
Length of a string
str1
All strings are terminated in NULL. This feature can
‘a’ ‘b’ ‘c’ ‘d’ ‘e’ ‘\0’
be used to manipulate strings
[0] [1] [2] 3] [4] [5]
For finding out length of a string → use a for loop
and keep on incrementing a counter till \0 is reached.

/* P2 Length of string */
#include <stdio.h>
#include <conio.h>
main()
{ char str[20];
int i;
printf("Enter the string - one word: ");
scanf("%s", str);
for (i=0; str[i] != '\0'; i++);
printf("\nNo. of characters in '%s' is %d", str, i);
getch();
}
Copy a string s1
= cannot be used for copying a string ‘a’ ‘b’ ‘c’ ‘\0’
S1[0] s1[1] S1[2] s1[3]
Copy character by character till the null character
and assign a NULL as the last character of new string. s2

/* P3 copy a string */ S2[0] s2[1] S2[2] s2[3]


#include <stdio.h>
#include <conio.h>
main()
{ char str1[20], str2[20];
int i;
printf("Enter the string : ");
gets(str1);
for (i=0; str1[i] != '\0'; i++)
str2[i] = str1[i];
str2[i] = '\0’;
printf("\nstr1 = %s\nstr2 = %s\n", str1, str2);
getch();
}
/*P4 Program to append two strings - concatenation */ s1
#include <stdio.h> ‘a’ ‘b’ ‘c’ ‘\0’
#include <conio.h> 0 1 2 3
main() s2
{ char s1[20], s2[20], s3[40]; ‘x’ ‘y’ ‘z’ ‘\0’
int i, j;
0 1 2 3
printf("Enter first string : ");
s3
gets(s1);
‘a’ ‘b’ ‘c’ ‘x’ ‘y’ ‘z’ ‘ \0’
printf("Enter second string : ");
gets(s2); 0 1 2 3 4 5 6 7
for (i=0; s1[i] != '\0'; i++)
s3[i] = s1[i]; Attaching s2 on s1 itself
for (j=0; s2[j] != '\0'; j++)
s3[i+j] = s2[j]; for (i=0; str1[i] != '\0'; i++);
s3[i+j] = '\0'; for (j=0; str2[j] != '\0'; j++)
printf("\n%s\t%s\t%s", s1, s2, s3); str1[i+j] = str2[j];
printf("\nLength of strings - %d %d %d\n", i, j, i+j); str1[i+j] = '\0';
getch();
} Size of s1 should be large enough
/*P5 Program to compare two strings */
main()
{ char x[40], y[40];
int i;
printf("\nEnter two strings - one word each: ");
scanf("%s%s", x, y);
for (i=0; x[i] == y[i] && x[i] != '\0' && y[i] != '\0'; i++);
if (x[i] == y[i])
printf("\nStrings are same\n");
else
printf("\nStrings are not same\n");
getch();
}
* If only the first condition is given, and if strings are same, then loop will go out of range.
* Condition to come out of loop are (i) any mismatch in characters
(ii) character become null for any of the string.
* Instead of for loop, while loop may be used
/*P6. Program to read a line of text, encrypt the text by replacing each
alphabet by the next alphabet. z should be replaced by a */ k b n f t
#include <stdio.h>
#include <conio.h> j a m e s
#include <string.h>
main()
s1
{ char s1[80], s2[80];
int i; a z a d \0
S1[0] S1[1] S1[2] S1[3] s1[4]
printf("Enter the string : ");
gets(s1); s2
for (i=0; s1[i] != '\0'; i++) b a b e \0
{ if (s1[i] == 'z') S2[0] S2[1] S2[2] S2[3] s2[4]
s2[i] = 'a';
else if (s1[i] == 'Z')
s2[i] = ‘A';
else
s2[i] = s1[i]+1;
}
s2[i] = '\0';
printf(“\nOriginal string %s\nEncripted string %s", s1, s2);
getch();
}
char city[30] = “Mumbai”;
String handling functions: strlen(city) → 6
#include <string.h> strlen(“Mumbai”) → 6
strlen(“city”) → 4
strlen() → finds length of string excluding null. strlen(“N Delhi”) → 7
n = strlen(str);
argument – variable or constant
char s1[10], s2[10] = “Gujarat”;
strcpy() → copies one string to another strcpy(s1, s2);
strcpy(s1, s2); s2 will be copied to s1 strcpy(s1, “Mumbai”);
s1 should be variable, s2 can be a variable or constant
char part1[ ] = “mile”, part2[ ] = “stone”;
strcat() → concatenate (append) two strings strcat(part1,part2);
strcat(s1, s2); s2 will be appended on s1 part1 → milestone
s1 should be variable, s2 can be a variable or constant part2 → stone

strcmp() → compares two strings char state[10] = “Gujarat”,


strcmp(s1, s2); return difference of first mismatch strcmp(state, “Gujarat”);
0 if s1 = s2 strcmp(“ROM”, “RAM”);
< 0 if s1 < s2 s1-s2 negative strcmp(“TEST”, “test” );
> 0 if s1 > s2 strcmpi(“Test”, “test”);
/*P7 Reverse a string and check for palindrome. * malayalam, madam, radar, peep,
A word which spell same forward and backward*/ * i selects characters from first to middle,
#include <string.h> A B C D E F \0 j selects them from last to middle.
main()
Loop stops when i >= j
{ int i, j, n; char temp;
char s[20], o[20]; * If swapping is not stopped at middle →
printf("\nEnter the string : "); result into the same string.
gets(s);
strcpy(o, s); * Reversing using a 2nd variable
n = strlen(s); for (i=0; i<n; i++)
for (i=0, j=n-1; i<j; i++, j--) s2[i] = s1[n-1-i];
{ temp = s[i]; s2[i] = '\0’
s[i] = s[j]; * Another logic
s[j] = temp; for (i=0; i<n/2; i++)
} { temp = s[i];
printf(“\n%s spelled backward is %s", o, s); s[i] = s[n-1-i];
if (strcmp(o, s) == 0) s[n-1-i] = temp;
printf(“\n%s is a palindrome”, s); }
else
printf(“\n%s is not a palindrome”, s);
getch();
}
/* P8 Write a program to read a string and rewrite it in alphabetical order */
#include <stdio.h> string → ginrst
#include <conio.h>
#include <string.h>
main()
{ char s[20], os[20], temp; printf("\nOriginal string : %s “, os);
int i, j, len; printf(“\nString in alphabetical order : %s“, s);
printf("\nEnter the string : "); getch();
gets(s); }
strcpy(os, s);
len = strlen(s);
for (i=0; i<len-1; i++)
{ for (j=0; j<len-1-i; j++)
{ if (s[j] > s[j+1])
{ temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
} } }
Table of strings:
S[4][7]
A list of names can be treated as table of strings or array of strings. ‘\0’
S[0] ‘a’ ‘b’ ‘c’ ‘d’
Two-dimensional character array, first index specifies number of S[1] ‘X’ ‘Y’ ‘Z’ ‘\0’
strings and second index specifies maximum length of each string. S[2] ‘1’ ‘2’ ‘3’ ‘4’ ‘5’ ‘6’ ‘\0’
e.g. char student [4][7]; S[3] ‘a’ ‘a’ ‘b’ ‘b’ ‘\0’

Once array is declared as two dimensional, it can be treated just as


array of strings for further manipulations .

To access an individual string, simply specify the left index only.


student [0] → name of first student
student [3] → name of 4th student
To print first character of all names
To print all names
for (i=0; i<4; i++) for (i=0; i<4; i++)
printf(“%s\n”, student[i]); printf(“%c\n”, student[i][0]);
/* P9 Program to sort a list of names in alphabetical order */
#include <stdio.h>
printf("\nSorted series\n");
#include <conio.h>
for (i=0; i<items; i++)
#include <string.h>
printf("%s\n", string[i]);
#define items 5 getch();
main() }
{ char string[items][20], dummy[20];
int i, j;
printf("\nEnter %d strings\n", items);
• Bubble sorting.
for (i=0; i<items; i++)
scanf("%s", string[i]); • Two-dimensional array is used to store list of
for (i=0; i<items-1; i++) strings, first index represents number of items
and second one size of individual array.
{ for (j=0; j<items-1-i; j++)
{ if (strcmp(string[j], string[j+1]) > 0) • scanf() function with %s format is used to read
{ strcpy(dummy, string[j]); strings inside a loop - Only one word.
strcpy(string[j], string[j+1]); • strcmp() function compares strings and returns a
strcpy(string[j+1], dummy); positive value if first string is alphabetically higher.
} } } * Dummy should be declared as a string of same size.
Home work - Strings

Q1. Write a program to read a line of text, generate a new string by removing all vowels
from the string. Print both strings

Q2. Write a program to read string containing number of words, print it one word per line.

You might also like