BBS514 Structured Programming (Yapısal Programlama)1 Character Processing, Strings and Pointers,

Slides:



Advertisements
Similar presentations
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
ECE Application Programming Instructor: Dr. Michael Geiger Spring 2012 Lecture 31: PE5.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
1 Lecture 7  Fundamental data types in C  Data type conversion:  Automatic  Casting  Character processing  getchar()  putchar()  Macros on ctype.h.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 8 - Characters and Strings Outline 8.1Introduction.
CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.
1 Review of Class on Oct Outline of Chapter 4  How to write a function?  Function Prototypes  Function Invocation  Function Definition  The.
Characters. COMP104 Lecture 21 / Slide 2 Data Type: char * Constant declaration const char star = '*'; * Variable declaration char resp; * Variable assignment.
1 Character Processing How characters can be treated as small integers? How characters are stored and manipulated in a machine? How use is made of certain.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
EPSII 59:006 Spring Introduction Fundamentals of Strings and Characters Character Handling Library String Conversion Functions Standard Input/Output.
Introduction to C programming
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
CHAPTER 8 CHARACTER AND STRINGS
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Chapter 8: Character and String CMPD144: Programming 1.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Sahar Mosleh California State University San MarcosPage 1 Character String.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
UniMAP SEM I - 09/10EKT 120 Computer Programming1 Lecture 8 – Arrays (2) & Strings.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Strings, Pointers and Tools
Characters and Strings
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 5 : September 4.
1 Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character Handling Library 8.4String Conversion.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
C Characters and Strings
Fundamentals of Characters and Strings
Character Processing How characters can be treated as small integers?
Lecture 8 String 1. Concept of strings String and pointers
Strings A string is a sequence of characters treated as a group
Arrays in C.
Chapter 8 - Characters and Strings
Character Processing How characters can be treated as small integers?
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Strings Adapted from Dr. Mary Eberlein, UT Austin.
C Characters and Strings
Presentation transcript:

BBS514 Structured Programming (Yapısal Programlama)1 Character Processing, Strings and Pointers,

The Data Type char BBS514 Structured Programming (Yapısal Programlama)2 Each character is stored in a machine in one byte (8 bits) –1 byte is capable of storing 2 8 or 256 distinct values. When a character is stored in a byte, the contents of that byte can be thought of as either a character or as an integer. A character constant is written between single quotes. ‘a’ ‘b’ A declaration for a variable of type char is char c; Character variables can be initialized char c1=‘A’, c2=‘B’, c3=‘*’;

BBS514 Structured Programming (Yapısal Programlama)3 lowercase‘a’‘b’‘c’...‘z’ ASCII value uppercase‘A’‘B’‘C’...‘Z’ ASCII value digit‘0’‘1’‘2’...‘9’ ASCII value other‘&’‘*’‘+’... ASCII value In C, a character is considered to have the integer value corresponding to its ASCII encoding.

Characters and Integers There is no relationship between the character ‘2’ (which has the ASCII value 50) and the constant number 2. ‘2’ is not 2. ‘A’ to ‘Z’ 65 to 90 ‘a’ to ‘z’ 97 to 112 Examples: –printf(“%c”,’a’); –printf(“%c”,97); have similar output. –printf(“%d”,’a’); –printf(“%d”,97); have also similar output. BBS514 Structured Programming (Yapısal Programlama)4

The Data Type char – nonprintable character Some nonprinting and hard-to-print characters require an escape sequence. For example, the newline character is written as \n and it represents a single ASCII character. Name of character Written in CInteger Value alert \a 7 backslash \\ 92 double quote \” 34 horizontal tab \t 9 BBS514 Structured Programming (Yapısal Programlama)5

Input and Output of Characters BBS514 Structured Programming (Yapısal Programlama)6 getchar ( ) reads a character from the keyboard. c = getchar(); /* variable c contains the next character of input */ putchar ( ): prints a character to the screen. putchar(c); /* prints the contents of the variable c as a character */

BBS514 Structured Programming (Yapısal Programlama)7 /* Illustrating the use of getchar( ) and putchar( ) */ #include int main (void) { char c; while ((c=getchar()) != EOF) { putchar(c); } EOF : It is control-d in Unix; control-z in DOS. abcdef aabbccddeeff

BBS514 Structured Programming (Yapısal Programlama)8 /* Capitalize lowercase letters and * double space */ #include int main(void) { int c; while ((c=getchar()) != EOF){ if (‘a’ <= c && c <= ‘z’) putchar(c+’A’-’a’); /*convert to uppercase*/ else if (c == ‘\n’){ putchar (‘\n’); } else putchar (c); } cop3223!c C

Character Functions Function Nonzero (true) is returned if isalpha(c) c is a letter isupper(c) c is an uppercase letter islower(c) c is a lowercase letter isdigit(c) c is a digit isalnum(c) c is a letter or digit isspace(c) c is a white space character Function Effect_____________ toupper(c) changes c to uppercase tolower(c) changes c to lowercase toascii(c) changes c to ASCII code BBS514 Structured Programming (Yapısal Programlama)9

10 /* Capitalize lowercase letters and double space */ #include int main(void) { int c; while ((c=getchar()) != EOF){ if (islower(c)) putchar(toupper(c)); /*convert to uppercase */ else if (c == ‘\n’){ putchar (‘\n’); } else putchar (c); }

Strings and Characters BBS514 Structured Programming (Yapısal Programlama)11 Characters –Building blocks of programs Every program is a sequence of meaningfully grouped characters –Character constant An int value represented as a character in single quotes 'z' represents the integer value of z Strings –Series of characters treated as a single unit Can include letters, digits and special characters ( *, /, $ ) –String literal (string constant) - written in double quotes "Hello" –Strings are arrays of characters in C String is a pointer to first character Value of string is the address of first character

Strings BBS514 Structured Programming (Yapısal Programlama)12 A string constant such as “a string” is an array of characters. Each element of the array stores a character of the string. In its internal representation, the array is terminated with the null character ‘\0’ so that the end of the string can be found easily. Thus, the length of the array is defined one more than the number of characters between the double quotes.

Declaring Strings BBS514 Structured Programming (Yapısal Programlama)13 char myString[10]; myString[0] = ‘H’; myString[1] = ‘e’; myString[2] = ‘l’; myString[3] = ‘l’; myString[4] = ‘o’; myString[5] = ‘\0’; ‘H’‘e’‘l’ ‘o’‘\0’????

Initializing Strings BBS514 Structured Programming (Yapısal Programlama)14 Character arrays can be initialized when they are declared : char name[5] ={‘T’,’E’, ‘S’,’T’,’\0’}; char name[5] = “TEST”; /*compiler automatically adds ‘\0’ */ char name[] = “TEST”; /*compiler calculates the size of the array */

Strings and Pointers BBS514 Structured Programming (Yapısal Programlama)15 We can declare and initialize a string as a variable of type char * char *color = “blue”; But the interpretation is different. “blue” is stored in memory as a string constant. The variable color is assigned the address of the constant string in memory. If we declare it as: char c[] = “blue”; the array c contains the individual characters followed by the null character.

Inputting Strings Using subscripts: char c, name[20]; int i; for (i = 0; (c = getchar())!=‘\n’; i ++) name[i] = c; name[i]=‘\0’; Using scanf and %s format: scanf(“%s”, name); –no need to use & operator –it will skip the leading blanks in the input, then characters will be read in. The process stops when a white space or EOF is encountered. –Remember to leave room in the array for '\0' BBS514 Structured Programming (Yapısal Programlama)16

Printing Strings Using %s format: printf(“%s %s\n”, “Nice to meet you”, name); Using subscripts: e.g. printing name backwards for (--i; i>=0; --i) putchar(name[i]); putchar(‘\n’); BBS514 Structured Programming (Yapısal Programlama)17

Examples BBS514 Structured Programming (Yapısal Programlama)18 printf("***Name:%8s*Lastname:%3s*** \n",“John", “Smith"); Output: ***Name: John*Lastname:Smith*** printf("***%-10s*** \n", “John"); Output ***John *** scanf("%d%s%d%s", &day,month,&year,day_name); Example input: 5 November 2001 Monday

BBS514 Structured Programming (Yapısal Programlama)19 String Handling Functions ( string.h ) String handling library has functions to –Manipulate string data –Search strings –Tokenize strings –Determine string length

String Handling Functions (cont.) unsigned strlen(char *s); –A count of the number of characters before \0 is returned. int strcmp(char *s1, char *s2 ); –Compares string s1 to s2 –Returns a negative number if s1 s2 int strncmp(char *s1, char *s2, int n ); –Compares up to n characters of string s1 to s2 –Returns values as above BBS514 Structured Programming (Yapısal Programlama)20

strcpy() and strncpy() We cannot change the contents of a string by an assignment statement. char str[10]; str = “test”; /*Error! Attempt to change the base address*/ Thus, we need to use string copy functions –strcpy(str, “test”); /*contents of str changed*/ –strncpy(str, “testing”, 5); str[5] =‘\0’;/* str contains testi only */ –strcpy(str, “a very long string"); /*overflow of array boundary */ BBS514 Structured Programming (Yapısal Programlama)21

strcat() and strncat() char s[8]=“abcd”; strcat(s,”FGH”); // s keeps abcdFGH char t[10]=“abcdef”; strcat(t,”GHIJKLM”); //exceeds string length! strncat(t, "GHIJKLM",3); t[9] = '\0';// t keeps abcdefGHI BBS514 Structured Programming (Yapısal Programlama)22

strcmp() and strncmp() We can compare characters with,<= etc. e.g. ‘A’ < ‘B’ But we cannot compare strings with the relational operators. e.g. str1 < str2 will compare the memory addresses pointed by str1 and str2. Therefore we need to use string comparison functions. strcmp("abcd", "abcde") ->returns a negative number strcmp("xyz", "xyz") -> returns zero strcmp("xyz", "abc") -> positive number strncmp("abcde", "abcDEF", 3) -> zero strncmp("abcde", "abcDEF", 4) -> positive number BBS514 Structured Programming (Yapısal Programlama)23

Examples char s1[] = “beautiful big sky country”; char s2[] = “how now brown cow”; Expression Value strlen(s1) 25 strlen(s2+8) 9 Statements What is printed printf(“%s”, s1+10); big sky country strcpy(s1+10, s2+8) strcat(s1, “s!”); printf(“%s”,s1); beautiful brown cows! BBS514 Structured Programming (Yapısal Programlama)24

BBS514 Structured Programming (Yapısal Programlama)25 int strlen (char *s) { int n; for (n = 0; *s!=‘\0’; s++) ++n; return (n); } int strlen (char *s) { int n=0; while (*s++){ //When s is pointing to the ++n; //null character, the value } // of *s is zero, causing the loop to //terminate. return (n); }

BBS514 Structured Programming (Yapısal Programlama)26 /* copy t to s; array subscript version */ void strcpy (char *s, char *t) { int i=0; while ((s[i] = t[i]) != ‘\0’) i++; } /copy t to s; pointer version */ void strcpy (char *s, char *t) { while (*s=*t)!=‘\0’){ s++; t++; } }

BBS514 Structured Programming (Yapısal Programlama)27 /* Concatenate two strings */ char *strcat(char *s1, char *s2) { char *p; p = s1; while (*p++); --p; while (*p++ = *s2++); return (s1); }

BBS514 Structured Programming (Yapısal Programlama)28 #include #define LENGTH 20 /* A string is a palindrome if it reads the same backwards and forwards. e.g. abba, mum, radar. This programs checks whether a given string is palindrome or not. int isPalindrome(char s[]); // function prototype int main() { char str[LENGTH]; // read the string printf(“Enter a string "); scanf("%s", str); // Check if it is a palindrome. if (isPalindrome(str)) printf("%s is a palindrome.\n", str); else printf("%s is not a palindrome.\n", str); }

BBS514 Structured Programming (Yapısal Programlama)29 int isPalindrome(char str[]) { int i, j, flag; i = 0; // index of the first character j = strlen(str) - 1; // index of the last character flag = 1; //assume it is a palindrome while ((i<j) && flag){ // compare the ith and jth. characters if (str[i] != str[j]) flag = 0; // if not same then string cannot be a //palindrome. else { i++; j--; } // advance to next characters } return flag; }

BBS514 Structured Programming (Yapısal Programlama)30 #include #include #define LENGTH 20 // This program converts a positive integer to a binary // number which is represented as a string. For instance // decimal number 12 is 1100 in binary system. void toBinary(int decVal, char *); //function prototype int main() { int num; char bin[LENGTH]; // read a positive integer printf(“Enter a number: "); scanf("%d",&num); // Convert the number and print it. toBinary(num, bin); printf(“Binary equivalent of %d is : %s",num,bin); }

BBS514 Structured Programming (Yapısal Programlama)31 void toBinary(int decVal, char *sb) { char s0[LENGTH], s1[LENGTH]; // create an empty string. strcpy(sb,””); if (decVal == 0) strcat(sb,"0"); // if number is zero result is 0 else // otherwise convert it to binary while (decVal != 0) { strcpy(s0,"0"); strcpy(s1,"1"); if (decVal%2 == 0) strcpy(sb,strcat(s0,sb)); //last character is 0 else strcpy(sb,strcat(s1,sb)); //last character is 1 decVal = decVal / 2; /* advance to find the next digit */ } return sb; }