CSC141- Introduction to Computer programming
description
Transcript of CSC141- Introduction to Computer programming
CSC141- Introduction to Computer programming
Teacher:
AHMED MUMTAZ MUSTEHSANAHMED MUMTAZ MUSTEHSANLecture – 21Lecture – 21
Thanks for Lecture Slides:http://blekko.com/ws/fundamentals+of+characters+and+stringsPrinciples of Programming - NI2005
CSC 141 Introduction to Computer Programming2
Fundamentals of Characters and Strings• In C language characters is either printable or
nonprintable including lowercase letters, uppercase letters, decimal digits, special characters and escape sequences.
• A character is usually stored in the computer as an 8-bits (1 byte) integer.
• The integer value stored for a character depends on the character set used by the computer on which the program is running.
CSC 141 Introduction to Computer Programming3
There are two commonly used character codes:
1.ASCII (American Standard Code for Information Interchange)
2.EBCDIC (Extended Binary Coded Decimal Interchange Code)
Fundamentals of Characters and Strings
CSC 141 Introduction to Computer Programming4
• char num = 1 and char num = ‘1’ are not the same.
• char num = 1 is represented in the computer as 00000001.
• char num = ‘1’ on the other hand is number 49 according to the ASCII character set. Therefore, it is represented in the computer as 00110001.
Difference Between an Integer Digit and a Character Digit
CSC 141 Introduction to Computer Programming5
Example: ASCII character#include <stdio.h>void main(void){
char A = 'A';char Z = 'Z';char a = 'a';char z = 'z';
printf("\nASCII value for A is %d\t", A);printf("\nASCII value for Z is %d\t", Z);printf("\nASCII value for a is %d\t", a);printf("\nASCII value for z is %d\t", z);
printf("\n");printf("\n Decimal 65 in ASCII represents %c\t",65);printf("\n Decimal 90 in ASCII represents %c\t",90);printf("\n Decimal 97 in ASCII represents %c\t",97);printf("\n Decimal 122 in ASCII represents %c\t",122);
}
CSC 141 Introduction to Computer Programming6
Sample outputASCII value for A is 65
ASCII value for Z is 90
ASCII value for a is 97
ASCII value for z is 122
Decimal 65 in ASCII represents A
Decimal 90 in ASCII represents Z
Decimal 97 in ASCII represents a
Decimal 122 in ASCII represents z
CSC 141 Introduction to Computer Programming7
Example cont…
#include <stdio.h> void main(void){
char ch; printf("enter a character: ");scanf("%c", &ch); if (ch >= 'A' && ch <= 'Z'){
printf("\ncapital letter\n");
}}
#include <stdio.h> void main(void){
char ch;
printf("enter a character: ");scanf("%c", &ch);
if (ch >= 65 && ch <= (65+26)){
printf("\ncapital letter\n");}
}
Both Examples are same
CSC 141 Introduction to Computer Programming8
Fundamentals of Characters and Strings• A string in C is an array of characters ending with the
null character (‘\0’).
• It is written inside a double quotation mark (“ ”)
• A string may be assigned (in a declaration) to either a char array or to a char pointer:
char color[] = “green”;
OR
char *color = “green”;
CSC 141 Introduction to Computer Programming9
• A string can also be defined by specifying the individual characters:
char name[ ] = {‘A’, ‘h’, ‘m’, ‘e’, ‘d’, ‘\0’};
• A string is accessed via a pointer to the first character in the string.
• In memory, the characters are stored as:
A h m e d \0
Fundamentals of Characters and Strings
CSC 141 Introduction to Computer Programming10
• For five characters string ‘Ahmed’, six characters are stored in the memory.
• Every string is terminated with a null character ‘\0’, which indicates the end of the string.
• For an array of characters to be stored as a string, the array must be large enough to store the string plus one terminating NULL character.
Fundamentals of Characters and Strings
CSC 141 Introduction to Computer Programming11
We can initialize string variables at compile time such as;
char name[10] = “Ahmed”;
The initialization will be stored in memory as :
A h m e d \0 \0 \0 \0 \0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
Briefly review about strings :
CSC 141 Introduction to Computer Programming12
Fundamentals of Characters and StringsIf we initialize the following string:
char string [4] = “milk”;
The system will generate the following syntax error:
error -------- array bounds overflow
Therefore, we need to declare the array with (the size of the string + 1) to accommodate the null terminating character ‘\0’.
char string [5] = “milk”;
CSC 141 Introduction to Computer Programming13
Example: string and ‘\0’#include <stdio.h>
/* The program that counts the number of characters in a string */
void main(void) { char string[] = "I love Pakistan";
count = 0;
for (int i = 0; string[i] != '\0'; i++) count++;
printf(“%s The string has %d characters including space", string, count);
}output:
I love Pakistan The string has 15 characters including space.
CSC 141 Introduction to Computer Programming14
Functions Inputscanf( )
gets( )
Functions Outputprintf( )
puts( )•Using scanf ( ) function with format specifier %s.•no whitespace character, as it terminates the input•If the string to be read has embedded spaces then use standard gets function.
strings I/O:
CSC 141 Introduction to Computer Programming15
Example: gets/puts and scanf/printf#include <stdio.h>
void main(void){ char string1[80]; char string2[80];
printf("Enter a sentence less than 80 characters with spaces: \n "); gets(string1);
printf("\nYou have entered: "); puts(string1);
printf("\n Entering a sentence less than 80 characters, with spaces: \n"); scanf("%s", string2);
printf("\nYou have entered: %s\n", string2); }
CSC 141 Introduction to Computer Programming16
/* Sample output */Enter a sentence less than 80 characters with spaces:My name is Ahmed
You have entered: My name is AhmedTry to entering a sentence less than 80 characters, with spaces:
Pakistan is my country
You have entered: Pakistan
More on gets() and puts() using pointers will be discussed in the next lecture
Example cont…
CSC 141 Introduction to Computer Programming17
Character Library• Character library contains several function that
perform useful tests of manipulating character data.
• Each function receives a character, represented as
an int as an argument.
• The header file <ctype.h> needs to be included, for using functions of the character library.
• These functions manipulates characters as integers (since a character is basically a 1 byte integer).
CSC 141 Introduction to Computer Programming
18
Prototype
Function Descriptions
int isdigit(int c) Returns a true if value c is a digit, and 0 (false) otherwise. int isalpha(int c) Returns a true if value c is a letter, and 0 otherwise. int isalnum(int c) Returns a true if value c is a digit or a letter, and 0 otherwise. int isxdigit(int c) Returns a true value if c is a hexadecimal digit character, and 0 otherwise. int islower(int c) Returns a true value if c is a lowercase letter, and 0 otherwise. int isupper(int c) Returns a true value if c is an uppercase letter, and 0 otherwise. int tolower(int c) If c is an uppercase letter, tolower returns c as a lowercase letter. Otherwise,
tolower returns the argument unchanged. int toupper(int c) If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise
toupper returns the argument unchanged. int isspace(int c) Returns true if c is a white space character – newline (‘\n’), space (‘ ’), form feed
(‘\f’), carriage return (‘\r’), horizontal tab (‘\t’) or vertical tab (‘\v’) – and 0 otherwise.
int iscntrl(int c) Returns a true if c is a control character, and 0 otherwise. int ispunct(int c) Returns a true if c is a printing character other than a space, a digit or a letter, and
0 otherwise. int isprint(int c) Returns a true value if c is a printing character including space (‘ ’), and 0
otherwise. int isgraph(int c) Returns a true value if c is a printing character other than space (‘ ’), and 0
otherwise.
CSC 141 Introduction to Computer Programming19
String Conversion Functions
These functions convert strings of digits to integer and floating-point values.
To use these functions, the general utilities library <stdlib.h>, needs to be included.
Note that these functions take a constant value as their argument. This means that we can only pass a constant string to the functions. Example:
atoi (“1234”);
const char *hello = “9999”;
atoi(hello);
CSC 141 Introduction to Computer Programming 20
Function Prototype Function Description
double atof (const char *nPtr) Converts the sting nPtr to double.int atoi (const char *nPtr) Converts the string nPtr to int.
long atol (const char *nPtr) Converts the string nPtr to long int.double strtod (const char *nPtr,
char **endptr)Converts the string nPtr to double.
long strtol (const char *nPtr, char**endptr, int base)
Converts the string nPtr long.
unsigned long strtoul (const char*nPtr, char **endptr, int base)
Converts the string nPtr to unsigned long.
nPtr - The pointer to the string to be converted.endptr - The pointer to which the remainder of the string will be assigned after the conversion. We can pass a NULL if the remaining string is to be ignored.base - Indicates the format (base) of the string to be converted. If 0 is given, that means the value to be converted can be in octal (base 8), decimal (base 10) or hexadecimal (base 16).
CSC 141 Introduction to Computer Programming21
Example/*1. Converting a String Into an int Using atoi. */#include <stdio.h> #include <stdlib.h>void main() {
char str1[ ] = "124z3yu87"; char str2[ ] = "-3.4"; char *str3 = "e24"; printf("str1: %d\n", atoi(str1)); printf("str2: %d\n", atoi(str2)); printf("str3: %d\n", atoi(str3));
}
Output:str1: 124 str2: -3 str3: 0
CSC 141 Introduction to Computer Programming22
Standard Input/Output Library Functions
Include <stdio.h> to use these functions.
Prototype of Function Description of Function int getchar (void) Get the next character from the standard input and return it as an integer
char *gets (char *s) Get characters from the standard input into the array s until a newline or end-of-file character is encountered. A terminating NULL character is
appended to the array.
int putchar (int c) Print the character stored in c
int puts (const char *s) Print the string s followed by a newline character
int sprint (char *s, const char *format, …)
Equivalent to printf except that the output is stored in the array s instead of printing on the screen
int sscanf (char *s, const char *format, …)
Equivalent to scanf except that the input is read from the array s instead of reading from the keyboard
CSC 141 Introduction to Computer Programming23
String Manipulation FunctionsInclude <string.h> to use these functions.
Prototype of Functions Description of Functions char *strcpy (char *s1, const char *s2) Copies the string s2 into the array s1. The value of s1 is returned
char *strncpy (char *s1, const char *s2, size_t n)
Copies at most n characters of the string s2 into the array s1. The value of s1 is returned.
char *strcat (char *s1, const char *s2) Appends the string s2 to the array s1. The first character of s2 overwrites the terminating NULL character of s1. The value of s1
is returned.
char *strncat (char *s1, const char *s2, size_t n)
Appends at most n characters of string s2 to array s1. The first character of s2 overwrites the terminating NULL character of s1.
The value of s1 is returned.
CSC 141 Introduction to Computer Programming24
String Comparison Functions
Include <string.h> to use these functions
Function Prototype Function Description int strcmp (const char *s1, const char *s2) Compares the string s1 to the string s2. The function returns
0, less than 0 (negative value), or greater than 0 if s1 is equal to, less than or greater than s2 respectively.
int strncmp (const char *s1, const char *s2, size_t n)
Compares up to n characters of the string s1 to the string s2. The function returns 0, less than 0, or greater than 0 if s1 is
equal to, less than or greater than s2 respectively.
CSC 141 Introduction to Computer Programming25
Example
int strcmp ( const char *s1, const char *s2 ); strcmp will accept two strings. It will return an integer. This integer will either be:
• Negative value if s1 is less than s2. • Zero value if s1 and s2 are equal. • Positive value if s1 is greater than s2.
strcmp is case sensitive. strcmp requires the address of the character array to be accessed.
CSC 141 Introduction to Computer Programming26
char *strcat ( char *dest, const char *src ); •The strcat is short name for string concatenate, •It means to add to the end, or append. •It adds the second string to the first string. •It returns a pointer to the concatenated string. •Make sure that the size of dest is large enough to hold the entire contents of src and dest string.
Example cont…
CSC 141 Introduction to Computer Programming27
char *strcpy ( char *dest, const char *src ); •strcpy is short for string copy. •It copies the entire contents of src into dest. •The contents of dest after strcpy will be exactly the same as src.
size_t strlen ( const char *s ); strlen returns the length of a string, minus the null character ('\0'). The size_t is a data type which is an integer that cannot be negative.
Example cont…
CSC 141 Introduction to Computer Programming28
#include <stdio.h> #include <string.h> void main() { char string1[50] = “COMSATS Institute of Information Technology"; char string2[50] = “COMSATS University”;
strcpy(string1,string2); printf(“string1: %s\n", string1); printf(“string2: %s\n", string2);
}
Output :string1: COMSATS Universitystring2: COMSATS University
Example: strcpy
CSC 141 Introduction to Computer Programming29
Example: strncpy
#include <stdio.h>#include <string.h>
void main(void){
char string1[100] = “Blochistan";char string2[50] = “Tajakistan";
strncpy(string2, string1, 5);printf(“string1: %s\n", string1);printf(“string2: %s\n", string2);
}Output:
string1: Blochistan
string2: Blochistan
CSC 141 Introduction to Computer Programming30
#include <stdio.h> #include <string.h> void main() {
char name[20] = “MUMTAZ"; char nameoft[20]; int correct = 0;
while(correct==0) {
printf("Enter the name of your teacher in uppercase: ");gets(nameoft);
if(strcmp(name, nameoft)==0) { printf("Correct!\n"); correct = 1; } else printf("Try again: \n");
} }
Example: strcmp
CSC 141 Introduction to Computer Programming31
You can only exit the program by entering "EDDIE". To perform a lowercase string comparison, use stricmp instead of strcmp but be warned: stricmp is NOT an ANSI C so it won't be supported by all C compilers.
Example cont…
CSC 141 Introduction to Computer Programming32
/* Concatenating Strings Using strcat */#include <stdio.h> #include <string.h> void main() {
char string1[50] = “Ahmed "; char string2[ ] = “Mumtaz"; strcat(string1, string2); printf("string1: %s\n", string1);
}Output:
string1: Ahmed Mumtaz
Defined the string1 array to be large enough to hold the characters of both strings.
Example: strcat
CSC 141 Introduction to Computer Programming33
Example: strncat
/* Concatenating Strings Using strncat */#include <stdio.h> #include <string.h> void main() {
char string1[50] = “Ahmed "; char string2[ ] = “Mumtaz"; strncat(string1, string2, 3); printf("string1: %s\n", string1);
}Output:
string1: Hello Mum
CSC 141 Introduction to Computer Programming34
Example: strlen
#include <stdio.h>#include <string.h>
void main(void){ char string[ ] = "I love Pakistan"; int i,count = 0; count = strlen(string); printf("%s The string has %d characters including the space“, string, count);}
output:
I love Pakistan The string has 15 characters including the whitespace
CSC 141 Introduction to Computer Programming35
String Search FunctionsInclude <string.h> to use these functions.
Function Prototype Function Description char *strchr (const char *s, int c) Locates the first occurrence of character c in string s. If c is found, s
pointer to c is returned. Otherwise a NULL pointer is returned.
size_t strcspn (const char *s1, const char *s2)
Determines and returns the length of the initial segment of string s1 consisting of characters not found in string s2.
size_t strspn (const char *s1, const char *s2)
Determines and returns the length of the initial segment of string s1 consisting only of characters contained in string s2.
char *strpbrk (const char *s1, const char *s2)
Locates the first occurrence of string s1 of any character in string s2. If a character from string s2 is found, a pointer to the character
in string s1 is returned. Otherwise a NULL pointer is returned.
char *strrchr (const char *s, int c) Locates the last occurrence of c in string s. If c is found, a pointer to c in string s is returned. Otherwise a NULL pointer is returned.
char *strstr (const char *s1, const char *s2)
Locates the first occurrence in string s1 of string s2. If the string is found, a pointer to the string in s1 is returned. Otherwise a NULL
pointer is returned. char *strtok (char *s1, const char
*s2) A sequence call to strtok breaks string s1 into “tokens” – logical pieces such as words in a line of text – separated by characters
contained in strnig s2. The first call contains s1 as the first argument, and subsequent calls to continue tokenizing the same
string contain NULL as the first argument. A pointer to the current token is returned by each call. If there are no more tokens when the
function is called, NULL is returned.
CSC 141 Introduction to Computer Programming36
SUMMARYStandard character-handling library of C, includes some useful functions for:•Testing types of characters•Converting letters to uppercase and lowercase.
C does not support strings as a data type. •use character arrays to represent strings.•Standard output functions printf, puts•Standard input functions scanf, gets
String manipulation functions •Copy strings, •Compare string, •Compute length of string,•Concatenate two strings to one