You are on page 1of 42

CSE-103

Structured Programming

Md. Mahbubur Rahman


Assistant Professor
Dept. Of CSE
Dhaka International University
Fundamentals of Characters and
Strings
⚫ Character constants: (which actually represents an integer value)
‘a’, ‘A’, ‘0’, ‘1’, ‘\n’, ‘ ’, ‘\0’
⚫ String constants:
“I am a student”, “Your score %d\n”
⚫ Character variable to store a character
char c = ‘l’;
⚫ Character array, which can store a string
char str[15] = “I am a student”;
or
char str[] = “I am a student”;
What are Strings?
⚫ The way a group of integers can be stored in an integer
array, similarly a group of characters can be stored in a
character array.
⚫ A string is a one-dimensional array of characters
terminated by a null character( ‘\0’ ).

//char array initializing while declaration


char a[] = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’};

//A string initialization during declaration


char str[] = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’};
OR
char str1[] = “HELLO”;
What is a NULL character (‘\0’)?
⚫ SLASH ZERO (‘\0’)
⚫ This character is the only way to find where the string
ends.
⚫ A string that is not terminated by a ‘\0’ is not a string.
It’s only a collection of characters (a character array)
String Literals
⚫ A string literal is a sequence of characters enclosed within double
quotes:
"When you come to a fork in the road, take it."
⚫ String literals may contain escape sequences.
⚫ Character escapes often appear in printf and scanf format
strings.
⚫ For example, each \n character in the string
"Candy\nIs dandy\nBut liquor\nIs quicker.\n --Ogden Nash\n"
causes the cursor to advance to the next line:
Candy
Is dandy
But liquor
Is quicker.
--Ogden Nash
Continuing a String Literal
⚫ The backslash character (\) can be used to continue a string
literal from one line to the next:
printf("When you come to a fork in the road, take it. \
--Yogi Berra");
⚫ In general, the \ character can be used to join two or more
lines of a program into a single line.
How String Literals Are Stored
⚫ When a C compiler encounters a string literal of length n in
a program, it sets aside n + 1 bytes of memory for the string.
⚫ This memory will contain the characters in the string, plus
one extra character—the null character—to mark the end of
the string.
⚫ The null character is a byte whose bits are all zero, so it’s
represented by the \0 escape sequence.
How String Literals Are Stored
⚫ The string literal "abc" is stored as an array of four
characters:

⚫ The string "" is stored as a single null character:


String Literals versus Character Constants

⚫ A string literal containing a single character isn’t the same


as a character constant.
⚫ "a" is represented by a pointer.
⚫ 'a' is represented by an integer.
⚫ A legal call of printf:
printf("\n");
⚫ An illegal call:
printf('\n'); /*** WRONG ***/
String Variables
⚫ If a string variable needs to hold 80 characters, it must be
declared to have length 81:
char str[80+1];
⚫ Adding 1 to the desired length allows room for the null
character at the end of the string.
⚫ Failing to do so may cause unpredictable results when the
program is executed.
Initializing a String Variable
⚫ A string variable can be initialized at the same time it’s
declared:
char date1[8] = "June 14";
⚫ The compiler will automatically add a null character so that
date1 can be used as a string:
Initializing a String Variable
⚫ If the initializer is too short to fill the string variable, the
compiler adds extra null characters:
char date2[9] = "June 14";
Appearance of date2:
Initializing a String Variable
⚫ An initializer for a string variable can’t be longer than the
variable, but it can be the same length:
char date3[7] = "June 14";
⚫ There’s no room for the null character, so the compiler
makes no attempt to store one:
Initializing a String Variable
⚫ The declaration of a string variable may omit its length, in
which case the compiler computes it:
char date4[] = "June 14";
⚫ The compiler sets aside eight characters for date4, enough
to store the characters in "June 14" plus a null
character.
⚫ Omitting the length of a string variable is especially useful if
the initializer is long, since computing the length by hand is
error-prone.
Printing Strings
#include<stdio.h>

int main(){
int i;
char str[] = "HELLO";

5
for(i = 0; i< ; i++)
printf("%c", str[i]);

return 0;
}
Printing Strings
#include<stdio.h>

int main(){
int i;
char str[] = "HELLO";
for(i = 0; str[i]!=‘\0’; i++)
printf("%c", str[i]);

return 0;
}
Printing Strings
#include<stdio.h>

int main(){
char str[] = "HELLO";
printf(“%s”,str);
printf(“%s”,str);
return 0;
}
Printing Strings
#include<stdio.h>

int main(){
char str[] = "HELLO";
puts(str); //It prints the string
puts(str); //and a newline
return 0;
}
Reading Strings Character by
Character
char str[100 ];
int i = 0;
char ch;
while ((ch = getchar()) != '\n')
{
if (i < 100 )
{
str[i++] = ch;
}
}
str[i] = '\0'; /* terminates string */

puts(str);
Taking a String Input
#include<stdio.h>

int main(){
char str[100];
printf("Enter your name:");
//scanf stops taking string input
//when it finds a whitespace character
scanf("%s",str);
printf("You name is %s\n",str);
return 0;
}
Taking a String Input
#include<stdio.h>

int main(){
char str[100];
printf("Enter your name:");
//gets stops taking string input
//when it finds a Newline character
gets(str);
printf("You name is %s\n",str);
return 0;
}
Don’t Underestimate scanf
#include<stdio.h>
int main(){
int d, m, y, ret;
printf("Enter day, month year: ");
ret = scanf("%d%d%d",&d,&m,&y);
printf("scanf returned: %d\n",ret);
printf("Day = %d\nMonth = %d\nYear = %d\n",d,m,y);
return 0;
}
Don’t Underestimate scanf
#include<stdio.h>
int main(){
int d, m, y, ret;
printf("Enter day, month year as (d/m/y) format:");
ret = scanf("%d/%d/%d",&d,&m,&y);
printf("scanf returned: %d\n",ret);
printf("Day = %d\nMonth = %d\nYear = %d\n",d,m,y);
return 0;
}
Don’t Underestimate scanf
#include<stdio.h>
int main(){
int d, m, y, ret;
printf("Enter day, month year as (d/m/y) format:");
ret = scanf("%d/%d/%d",&d,&m,&y);
printf("scanf returned: %d\n",ret);
printf("Day = %d\nMonth = %d\nYear = %d\n",d,m,y);
return 0;
}
Don’t Underestimate scanf
#include<stdio.h>
int main(){
int d, m, y, ret;
printf("Enter day, month year as (d/m/y) format:");
ret = scanf("%d-%d-%d",&d,&m,&y);
printf("scanf returned: %d\n",ret);
printf("Day = %d\nMonth = %d\nYear = %d\n",d,m,y);
return 0;
}
Don’t Underestimate scanf
#include<stdio.h>

int main(){
char str[100];
printf("Enter your name: ");
scanf("%s",str);
printf("Your name is %s\n",str);
return 0;
}
Don’t Underestimate scanf
#include<stdio.h>

int main(){
char str[100];
printf("Enter your name: ");

"%[abcd]",str);
scanf(
printf("Your name is %s\n",str);
return 0;
}
Don’t Underestimate scanf
#include<stdio.h>

int main(){
char str[100];
printf("Enter your name: ");

"%[a-zA-Z]",str);
scanf(
printf("Your name is %s\n",str);
return 0;
}
Don’t Underestimate scanf
#include<stdio.h>
int main(){
char str[100];
printf("Enter your name: ");

"%[a-zA-Z 0-9\t]",str);
scanf(
printf("Your name is %s\n",str);
return 0;
}
Don’t Underestimate scanf
#include<stdio.h>
int main(){
char str[100];
printf("Enter your name: ");

"%[^abcd]",str);
scanf(
printf("Your name is %s\n",str);
return 0;
}
Don’t Underestimate scanf
#include<stdio.h>
int main(){
char str[100];
printf("Enter your name: ");

"%[^abcd]",str);
scanf(
printf("Your name is %s\n",str);
return 0;
}
Don’t Underestimate scanf
#include<stdio.h>
int main(){
char str[100];
printf("Enter your name: ");

"%[^\n]",str);
scanf( //Similar to gets(str)
printf("Your name is %s\n",str);
return 0;
}
String Library(string.h) functions
//strlen():
#include<stdio.h>
#include<string.h>

int main(){
int len;
char str[100];
gets(str);
len = strlen(str);
printf("Length of string = %d\n",len);
return 0;
}
String Library(string.h) functions
#include<stdio.h>
#include<string.h>

int main(){
int len;
char str1[100], str2[100];
gets(str1);
strcpy(str2,str1);
printf("String 1 = %s\n",str1);
printf("String 2 = %s\n",str2);

return 0;
}
String Library(string.h) functions
//strcat
#include<stdio.h>
#include<string.h>
int main(){
int len;
char str1[100], str2[100];
printf("Enter first string:");
gets(str1);
printf("Enter second string: ");
gets(str2);
strcat(str1,str2);
printf("String 1 = %s\n",str1);
printf("String 2 = %s\n",str2);
return 0;
}
String Library(string.h) functions
//strcmp
#include<stdio.h>
#include<string.h>
int main(){
int len, retVal;
char str1[100], str2[100];
printf("Enter first string:");
gets(str1);
printf("Enter second string: ");
gets(str2);
retVal = strcmp(str1,str2);
if(retVal == 0)
printf("str1 and str2 are both equal\n");
else if(retVal > 0)
printf("str1 is below str2 in a dictionary\n");
else if(retVal < 0)
printf("str1 is above str2 in a dicationary\n");
return 0;
}
Building a Spell Checker
#include<stdio.h>
#include<string.h>
#include<conio.h>

int main(){
//This dictionary will contain at most 100 strings
//Each string may have length at most 19 characters
char dictionary[100][20];
char word[20];
int i, found, j;
Building a Spell Checker
//Take words input to the dictionary
printf("Build the dictionary:(EOF to break)");

i = 0;
while(gets(dictionary[i])!=NULL)
i++;

//Now we have i number of words in the dictionary


Building a Spell Checker
printf("Enter a word to check:");
gets(word);

//Search in the dictionary


found = 0;
for(j = 0; j<i; j++){
if(strcmp(dictionary[j],word)==0){
found = 1;
break;
}
}
if(found==0){
printf("\"%s\" not found\n",word);
}else{
printf("\"%s\" found in dictionary\n",word);
}
Building a Spell Checker

return 0;
}
Sort the dictionary (in lexicographical order
//Now we have i words in the dictionary
N = i;
//Sort the dictionary in lexicographical order
//that means ascending order
for(i = 0; i< N-1; i++){
for(j = 0; j<N-i-1; j++){
//if(a[j] > a[j+1])
if(strcmp(dictionary[j],dictionary[j+1])>0){
//Swap a[j] with a[j+1]
//t = a[j];
strcpy(t,dictionary[j]);

//a[j] = a[j+1];
strcpy(dictionary[j], dictionary[j+1]);

//a[j+1] = t;
strcpy(dictionary[j+1],t);
}
}
}
Sort the dictionary (in lexicographical order
//Let's check the dictionary
for(i = 0; i<N; i++)
{
printf("Word %d: %s\n",i, dictionary[i]);
}
return 0;
}

You might also like