מחרוזות-String בשפת C++ ישנו תפקיד מיוחד למערך מסוג char רצף של תווים הנמצאים במערך מסוג char המסתיימת בתו אפס (הכוונה לאפס ממש '0\' , ולא לתו '0')

Slides:



Advertisements
Similar presentations
LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Advertisements

Introduction to Data Structure, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Standard Template Library Ming.
Friday, January 05, 2007 A few weeks of developing and testing can save a whole afternoon in the library. -Anonymous.
Lab 7 strings as arrays of chars. #include #include #include using namespace std; int printMenu( ); int hexSymbolValue( char c ); int readBinValue( bool.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
1 Stacks Stack Examples Stack API More Examples/Uses Base Conversion Activation Records RPN Implementing a Stack Stacks.
Chapter 8 Strings and Vectors (8.1 and 8.2). An Array of characters Defined as: char firstName[20]; char firstName[] = {‘T’, ‘i’, ‘m’}; // an array of.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
String Constructors string str; // creates an empty //string string str(“abc”); // creates a string // from a C-string string str(aString); // creates.
Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Lecture 17: Characters, Strings, and the string class Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
CS1201: Programming Language 2 Recursion By: Nouf Almunyif.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
CS31: Introduction to Computer Science I Discussion 1A 4/16/2010 Sungwon Yang
String Class. C-style and C++ string Classes C-style strings, called C-strings, consist of characters stored in an array ( we’ll look at them later) C++
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture.
CS 1430: Programming in C++ 1. Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
Sahar Mosleh California State University San MarcosPage 1 Character String.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Strings. Using strings as abstract value A string is a sequence of characters e.g. “Hello, World!” Early version of C++ followed the older C language.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Enumerated Types and Strings Types.
Strings.
CSCE 210 Data Structures and Algorithms
LESSON 2 Basic of C++.
Command Line Arguments
לולאות קרן כליף.
Quiz Next Monday.
Dynamic Memory Allocation Reference Variables
Programming -2 برمجة -2 المحاضرة-5 Lecture-5.
Random Number Generation
פונקציות לעיתים קרובות לא נוח להגדיר את כל התוכנה בתוך גוף אחד.
Learning Objectives String Class.
אבני היסוד של תוכנית ב- C++
אבני היסוד של תוכנית ב- C++
הרצאה 03 אבני היסוד של תוכנית ב- C
Strings A collection of characters taken as a set:
Starting Out with C++: From Control Structures through Objects
Pointers & Functions.
اصول کامپیوتر ۱ مبانی کامپیوتر و برنامه‌سازی
Chapter 9 One-Dimensional Arrays
Code::Block vs Visual C++
String class and its objects
String in C++.
Engineering Problem Solving with C++, Etter
Jeff West - Quiz Section 4
CS1201: Programming Language 2
Arrays of Two-Dimensions
Lecture 8-2 : STL Iterators and Algorithms
Using string type variables
Pointers & Functions.
(Dreaded) Quiz 2 Next Monday.
Std Library of C++.
Today’s Objectives 28-Jun-2006 Announcements
CS-161 Computer Programming Lecture 15 & 16: Arrays II
CS31 Discussion 1D Winter19: week 4
Programming Strings.
Library in c++ ( as cmath , iostream , …… etc.)
character manipulation
Instructor: Dr. Michael Geiger Spring 2019 Lecture 6: Strings
An Introduction to STL.
Announcements Exam 2 Lecture Grades Posted on blackboard
CSE Module 1 A Programming Primer
Presentation transcript:

מחרוזות-String בשפת C++ ישנו תפקיד מיוחד למערך מסוג char רצף של תווים הנמצאים במערך מסוג char המסתיימת בתו אפס (הכוונה לאפס ממש '0\' , ולא לתו '0') משמשת ב- C++ כמחרוזת. '0\' -הוא סימון שכאן מסתיימת המחרוזת. המחרוזת לא חייבת לתפוס את כל המערך. '0\' הוא למעשה מוסכמה, על מנת שלא נהיה צריכים לשלוח לפונקציה את אורך המחרוזת .  

char word[10]; זה מערך של תווים word[0] = ‘a’; עדיין word[1] = ‘b’; עדיין word[2] = ‘a’; עדיין word[3] = ‘\0’; עכשיו אפשר להגיד שזו מחרוזת, וגם אפשר להגיד שזה מערך של תווים אפשר לעשות אותה פעולה ע"י char word[10] = “aba”; המהדר מסיק שמדובר במחרוזת ומוסיף אוטומטית את ה-0/ בסוף . a b \0 d F s z E

עוד דוגמה: #include <iostream> #include <string> using namespace std; void f1() { char str[20] = {'I',' ','L','o','v','e',' ','C','+','+','\0'}; cout<<str<<endl; cout << "size of char array is "<<strlen(str) << endl; } int main() f1(); return 0; בדוגמה זו רואים שלמרות שאורך המערך הוא 20 תווים, אורך המחרוזת רק 10. כדי להכיל את המחרוזת דרושים 11 מקומות ולא 10 כדי להכיל את האפס המסיים. נשאלת השאלה מה נמצא ב-9 המקומות האחרונים והתשובה היא, שלא ניתן לחזור כמו בכל מקום שלא אותחל. strlen-פונקציה שמחזירה גודל של מערך התווים..  

cout << str << endl; אתחול מחרוזות מכיוון שמחרוזות נפוצות כל כך הגדירו צורת אתחול מיוחדת. אתחול מחרוזת מתבצע על-ידי רשימה בתוך מירכאות. האפס המסיים (NULL) מוכנס באופן אוטומטי, למרות שלא נרשם.   void f2() { char str[20] = "I Love C++"; cout << str << endl; cout << "size of char array is " << strlen(str) << endl; }

צורת אתחול נוספת אשר ניתן לבצע היא על-ידי השמה של כל איבר לחוד כמו במערך:   void f3() { char str[20]; str[0] = 'I'; str[1] = ' '; str[2] = 'L'; str[3] = 'o'; str[4] = 'v'; str[5] = 'e'; str[6] = ' '; str[7] = 'C'; str[8] = '+'; str[9] = '+'; str[10] = ' '; str[11] = '\0'; cout<<str<<endl; }

ספריית string בספרייה זו הוגדר טיפוס חדש של מחרוזת - string:   #include <iostream> #include <string>  using namespace std; void f4() { string s1 = "To be or not to be"; cout<<"s1: "<<s1<<endl; string s2; cout << "enter string: "; cin>>s2; cout<<" s2: "<<s2<<endl; } int main() f4(); s1: To be or not to be enter string: i love c s2: i Press any key to continue . . .

בדוגמה זו רואים שפקודה cin קולטת רק את התווים עד רווח ראשון בדוגמה זו רואים שפקודה cin קולטת רק את התווים עד רווח ראשון. כדי לקלוט את כל המחרוזת עלינו להשתמש בפונקציה getline הנמצאת בספריית string: void f5() { string s1; cout << "enter string: "; getline(cin, s1);; cout<<" s1: "<<s1<<endl; } int main() f5(); enter string: i love c s1: i love c Press any key to continue . . .

השמה: void f6() { string s = "hello world",s1,s2; s1 = s; cout << "s: "<<s<<" s1: "<<s1<<endl; s2 = "abc def"; cout<<"s2: "<<s2<<endl; s2[0] = 'x'; s2[1] = 'y'; s2[2] = 'z'; char c = 'o'; s2[3] = c; string s3 = s1+s2; cout<<"s3: "<<s3<<endl; } int main() f6();   פלט: s: hello world s1: hello world s2: abc def s2: xyzodef s3: hello worldxyzodef Press any key to continue . . .

פונקציות של ספרייה String פונקציות הספרייה הגדרה: string s, s1; char c; אורך המחרוזת: int i = s.length() – int i = s.size() - אם המחרוזת ריקה (פונקציה בוליאנית) if (s.empty()) i++; if (s == "") i++;  תת-מחרוזת: s1 = s.substr(start, len) s[start, . . .,start+len-1] הפונקציה מחזירה תת-מחרוזת  

i = s.find(s1); חיפוש מקום שמאלי ביותר של מופעה בתוך מחרוזת מחרוזת חיפוש: i = s.find(c); חיפוש מקום שמאלי ביותר של מופעה תו בתוך מחרוזת i = s.find(s1); חיפוש מקום שמאלי ביותר של מופעה בתוך מחרוזת מחרוזת i = s.find(s1, start); חיפוש מקום שמאלי ביותר של מופעה מחרוזת בתוך מחרוזת החיפוש מתחיל ממקום start השוואה: i = s.compare(s1); 0 > i כאשר s < s1 0 = i כאשר s == s1 0 < i כאשר s < s1   החלפה: s.replace(start, num,s2) ; החלפת תת-מחרוזת של s שמתחילה במקום start ואורכה num בתת-מחרוזת 2s.

דוגמה של מימוש ב-C++   #include <iostream> #include <string> using namespace std; void f1() { char str[20] = {'I',' ','L','o','v','e',' ','C','+','+','\0'}; cout<<str<<endl; } void f2() char str[20] = "I Love C++";

void f3() { char str[20]; str[0] = 'I'; str[1] = ' '; str[2] = 'L'; str[3] = 'o'; str[4] = 'v'; str[5] = 'e'; str[6] = ' '; str[7] = 'C'; str[8] = '+'; str[9] = '+'; str[10] = ' '; str[11] = '\0'; cout<<str<<endl; }

void f4() { string s1 = "To be or not to be"; cout<<"s1: "<<s1<<endl; string s2; cout << "enter string: "; cin>>s2; cout<<" s2: "<<s2<<endl; } void f5() string s1; getline(cin, s1); cout<<" s1: "<<s1<<endl;

void f6() { string s = "hello world",s1,s2; s1 = s; cout << "s: "<<s<<" s1: "<<s1<<endl; s2 = "abc def"; cout<<"s2: "<<s2<<endl; s2[0] = 'x'; s2[1] = 'y'; s2[2] = 'z'; char c = 'o'; s2[3] = c; string s3 = s1+s2; cout<<"s3: "<<s3<<endl; }

void flen() { string s="to be or not to be"; int i = s.length(); cout <<"length = "<<i<<" size = "<<s.size()<<endl; bool b = s.empty();// 0 - false, 1 - true cout << "is empty? " << b << endl; s = ""; cout<<"s="" is empty?"<<s.empty() << endl;} /// find void ffind() // substring string s1 = s.substr(0, 5); cout<<"substring: "<<s1+"!"<<endl; char c='b'; // find int i = s.find(c); cout<<"s.find(c): "<<i<<endl; cout<<"find(be) "<<s.find("be")<<endl; cout<<"find(be) "<<s.find("be",4)<<endl; }

void fcompare() { // compare string s="to be or not to be"; cout <<s.compare("xyz")<<endl; cout <<s.compare("be")<<endl; cout <<s.compare("to be or not to be")<<endl; } void freplace() // replace s.replace(3,2,"study"); s.replace(19, 2 ,"study"); cout<<s<<endl;  

int main() { flen(); ffind(); fcompare(); freplace(); return 0; }   פלט:

int string_count(string s1,string s2) { int count=0,index; for(int i=0;i<s1.length();i++) } index=s1.find(s2,i); if(index!=-1) count++; i=index+1; return count;