1 بنام خدا زبان برنامه نویسی C (21814( Lecture 13 Chapter 13 Strings.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
 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 09 Strings, IDEs. METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan Mon July 29, 2002.
Character String Manipulation. Overview Character string functions sscanf() function sprintf() function.
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.
Strings CS240 Dick Steflik. What is a string A null terminated array of characters: char thisIsAString[10]; \0 The “\0” (null character)
 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.
Chapter Fourteen Strings Revisited. Strings A string is an array of characters A string is a pointer to a sequence of characters A string is a complete.
Chapter 9 Strings Instructor: Alkar / Demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.9-2 Strings stringC implements the string data.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
C programming---String. String Literals A string literal is a sequence of characters enclosed within double quotes: “hello world”
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
N-1 University of Washington Computer Programming I Lecture 19: Strings © 2000 UW CSE.
C-Strings A C-string (also called a character string) is a sequence of contiguous characters in memory terminated by the NUL character '\0'. C-strings.
Introduction to C Programming CE Lecture 13 Strings in C.
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
Strings String - a string is a series of characters treated as a unit. A C string is a variable-length array of characters that is delimited by the null.
CS 201 String Debzani Deb.
Exercise 7 Strings. An array of characters Used to store text Another way to initialize: char A[ ]=“blabla”;
String What it is Why it’s useful library routines for handling strings how to input a string from the keyboard.
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.
Introduction to C programming
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.
BBS514 Structured Programming (Yapısal Programlama)1 Character Processing, Strings and Pointers,
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
CPT: Strings/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to discuss strings and their relationship.
CS 162 Introduction to Computer Science Chapter 17 C++ String Objects Herbert G. Mayer, PSU (Copied from Prof. Phillip Wong at PSU) Status 11/30/2014.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
File IO and command line input CSE 2451 Rong Shi.
APS105 Strings. C String storage We have used strings in printf format strings –Ex: printf(“Hello world\n”); “Hello world\n” is a string (of characters)
מערכים (arrays) 02 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 15 1 Department of Computer Science-BGU.
Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 6 Array and String.
1 This chapter covers both string constants (or literals, as they're called in the C standard) and string variables, which can change during the execution.
5-1 Embedded Systems C Programming Language Review and Dissection III Lecture 5.
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:
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. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
String Array (Multidimensional Arrays) 1. A string array is a multidimensional array of strings. It is declared in the following syntax: char variable_name[No_of_strings][size_of_each_string];
Strings, Pointers and Tools
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
Today’s Material Strings Definition Representation Initialization
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.
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.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
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.
Strings CSCI 112: Programming in C.
INC 161 , CPE 100 Computer Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
ECE Application Programming
Strings (Continued) Chapter 13
Lecture 8 String 1. Concept of strings String and pointers
CSE 303 Lecture 14 Strings in C
String What it is Why it’s useful
EECE.2160 ECE Application Programming
Chapter 8 Character Arrays and Strings
Presentation transcript:

1 بنام خدا زبان برنامه نویسی C (21814( Lecture 13 Chapter 13 Strings

2 زبان برنامه نویسی C (21814 ( فصل سیزدهم در این فصل نحوه ترکیب data type های معرفی شده در فصول قبلی با هم به منظور ایجاد برنامه های پیچیده تر مورد بررسی قرار می گیرند.

3 Strings (and Things)

4 زبان برنامه نویسی C (21814 ( فصل سیزدهم Arrays of characters آرایه ای شامل کاراکتر را بصورت زیر در نظر بگیرید: char c[11] = {'c','h','a','r','s','t', 'r','i','n','g','s'}; c charstringscharstrings

5 زبان برنامه نویسی C (21814 ( فصل سیزدهم Strings خروجی عبارت زیر را در نظر بگیرید: printf("%s", "charstrings"); c h a r s t r i n g s \0 '\0' has numerical value 0. It's called the null character.

6 زبان برنامه نویسی C (21814 ( فصل سیزدهم Null Pointer vs. Character Don't confuse these two NULL = null pointer = address (4 bytes) with value zero. It's a constant defined in. Returned by fopen() when error. '\0' = null character = character (1 byte) with value zero. Used as last character of a string to indicate it's end.

7 زبان برنامه نویسی C (21814 ( فصل سیزدهم Strings have null termination The character '\0' (null character) terminates every string (ASCII value 0). The purpose is to delimit (i.e. mark) the end of the string. This allows functions (like printf()) to process strings without knowing length ahead of time.

8 زبان برنامه نویسی C (21814 ( فصل سیزدهم Strings = Arrays of chars A string is a null character terminated array of characters. The value of a string is the address of it’s first character! Thus a constant string functions as a constant pointer.

9 زبان برنامه نویسی C (21814 ( فصل سیزدهم Strings and Pointers Initialization in declaration char a[] = "xyz"; char a[] = {'x', 'y', 'z', '\0'}; // same thing char *p = "xyz"; // pointer initialization Assignment char *p; p = "xyz";// p points to 'x'

10 زبان برنامه نویسی C (21814 ( فصل سیزدهم No automatic copy in C char a[50], *p, b[ ] = "abcdef"; p = b;// OK, assignment of address p = "xyz"; // OK, addr. assignment again a[ ] = b[ ];// NO! doesn't work a = b;// NO! a is a constant

11 زبان برنامه نویسی C (21814 ( فصل سیزدهم string declaration and memory p a b c \0 pa char *p;char *p = "abc"; char a[3]; char a[] = "abc"; a b c \0 ??? a

12 زبان برنامه نویسی C (21814 ( فصل سیزدهم Using a pointer to process a string Finding the length of a string #include int len(char *p) { int count=0; while (*p++) ++count; /* counts chars in string */ return count; } void main(void){ char *s = "12345"; printf("%d", len(s));/* prints number 5 */ printf("\n\n"); } null char at end of string makes the loop stop.

13 زبان برنامه نویسی C (21814 ( فصل سیزدهم String handling functions scanf(), gets(), fgets(): in. These require #include strlen(): length of a string. strcpy(): copy a string. strcat(): concatenate a string. strchr(), strrchr(): search for a character. strstr(): search for a substring. strcmp(): compare two strings.

14 زبان برنامه نویسی C (21814 ( فصل سیزدهم int scanf(const char *,...) char a[80]; scanf("%s", a); // could use scanf("%s", &a[0]) for( int i=0; i<=80;i++){ printf("%c",a[i]); } Reads from KB until white space encountered. Copies into a[ ]. "This is a string" as input will fill a[ ] with "This" only. Thus can be only used to input single words.

15 زبان برنامه نویسی C (21814 ( فصل سیزدهم char *gets(char *) char a[80]; gets(a); Copies characters from keyboard into a[ ] up to but not including the newline. Copies everything including white space. Puts '\0' at end. Must be enough room in a[ ] for the input!

16 زبان برنامه نویسی C (21814 ( فصل سیزدهم char * fgets(char * str, int n, FILE * fp) Reads a string from a file and stores in array pointed to by str. Stops reading when n characters read or when '\n' read, whichever comes first. The '\n' will be stored in the string.

17 زبان برنامه نویسی C (21814 ( فصل سیزدهم int strlen(const char * s) char *s = "This string is 27 char long“ printf("%d", strlen(s)); Prints the value 27 Does not count the '\0' at the end.

18 زبان برنامه نویسی C (21814 ( فصل سیزدهم char *strcpy(char * s, const char * t) char s[10], t[ ] = "12345"; strcpy(s, t); printf("%s", s); /*or printf("%s", strcpy(s,t)); */ prints the string "12345" You must make sure s[ ] is big enough to hold all of the characters of t[ ]! if declared s[3], then BIG TROUBLE.

19 زبان برنامه نویسی C (21814 ( فصل سیزدهم int strcmp(const char * s, const char * t) char s[ ]="smith", t[ ]="smyth"; n = strcmp(s, t);/* n is negative */ n= strcmp(t, s);/* n is positive */ n = strcmp(s, s);/* n is zero, */ This function is used for sorting words alphabetically.

20 زبان برنامه نویسی C (21814 ( فصل سیزدهم char *strcat(char *s, const char * t); char s[20], t[] = "bea", u[] = "vers"; strcpy(s, t); /* copies t to s */ strcat(s, u); /* s[] now contains "beavers" */ Appends (concatenates) second string onto end of first (starting at '\0' position). You must have room in s[] or again there will be TROUBLE. If s[3] declared, it won’t work (sometimes).

21 char *strchr(const char * s, int ch) char * strrchr(const char * s, int ch) Searches s for a character and returns pointer to the character -- strchr() from the start, strrchr() from the end. char s[] ="The quick sly beaver jumped over the lazy white duck"; strchr(s, 'y') points to here. strrchr(s, 'y') points to here.

22 زبان برنامه نویسی C (21814 ( فصل سیزدهم char *strstr(const char * s, const char * t) Searches s for a substring, t and returns pointer to the beginning of the substring char s[ ] ="The quick sly beaver jumped over the lazy white duck"; strstr(s, "jumped") points to here.

23 زبان برنامه نویسی C (21814 ( فصل سیزدهم Monkey Works Given enough time could a monkey typing randomly, create Hamlet? See how long is takes a monkey to type a given word. Make a function that types randomly until it matches a given word.

24 زبان برنامه نویسی C (21814 ( فصل سیزدهم Monkey Works int main(void) { char name[20]; printf("type a name: ");// prompt the user scanf("%s", name); // for a name // and print out the results printf("\n\nIt only took him %d tries to type %s", fastMonkey(name), name); return 0; }

25 زبان برنامه نویسی C (21814 ( فصل سیزدهم fastMonkey function int fastMonkey(char *name) { char alpha[] = "abcdefghijklmnopqrstuvwxyz"; char test[20]; // the output of the random typing int done = 0, count = 0, i; while(!done) { // loop until typing is successful for(i = 0; i < strlen(name); ++i) // create test same length as 'name' test[i] = alpha[rand() % 26]; test[i] = '\0';// make 'test' a string if(strcmp(test, name) == 0)// check if matches done = 1; ++count; if(count % INC == 1) {// print out progress printf("%d ", count/INC); fflush(stdout); } return count; }

26 زبان برنامه نویسی C (21814 ( فصل سیزدهم myScanf for Strings Make a function that acts like scanf("%s", word) given the declaration. char word[30]; i.e. reads word from KB and puts in word[ ]

27 زبان برنامه نویسی C (21814 ( فصل سیزدهم myScanf() code int myScanf(char *s) { int inChar; while (isspace(inChar = getchar())) ;// skip white space while ( !isspace(inChar) && inChar != EOF) { *s++ = inChar;// copy while not whitespace or EOF inChar = getchar(); /*/ and get the next char } *s = '\0';// make it a string if( inChar == EOF) return EOF;// if at end, tell the caller else return 1;// number of words found }

28 زبان برنامه نویسی C (21814 ( فصل سیزدهم Use myScanf to Count Words int main (void) { char word[30]; int count = 0; while(myScanf(word) != EOF){ ++count; // get words from KB and count // printf("%s\n", word); } printf("\nCounted %d words\n\n", count); return 0; }

29 زبان برنامه نویسی C (21814 ( فصل سیزدهم EC6 -- myScanf() for Integers make a myScanf() function that works like scanf("%d", &val) for positive integers. i.e. myScanf(int * p) reads digit characters from KB (use getchar()) and converts to integer. –skips white space. –reads digits and converts to integer until –non-digit read, then stores in integer at *p You should be able to replace a call to scanf("%d", &val) with myScanf(&val).