This chapter discusses user-defined simple data types in C++ including enumeration types, typedef statements, namespaces, and the string type. It covers creating enumeration types and anonymous data types, using typedef to create type aliases, how namespaces avoid name collisions, and functions for manipulating strings like length(), find(), substr(), and swap(). The chapter includes an example program that converts strings to "pig Latin" form using string functions.
The document provides an overview of data structures and algorithms. It discusses key topics like:
1) Different types of data structures including primitive, linear, non-linear, and arrays.
2) The importance of algorithms and how to write them using steps, comments, variables, and control structures.
3) Common operations on data structures like insertion, deletion, searching, and sorting.
4) Different looping and selection statements that can be used in algorithms like for, while, and if-then-else.
5) How arrays can be used as a structure to store multiple values in a contiguous block of memory.
Arrays allow the grouping of multiple values of the same type under a single name. An array is declared with a base type and size, and individual elements can be accessed via an index. Arrays are useful for organizing related data and can be passed to methods. Common array operations include initialization, accessing elements, searching, and sorting. Multidimensional arrays extend the concept to multiple indices.
Arrays allow us to organize multiple values of the same type into a single variable name. An array is declared with square brackets containing the number of elements, and individual elements are accessed via an index number. Arrays can be passed as arguments to methods, where the method can modify class-type elements but only sees the value of primitive-type elements. Array names are reference types, so assigning one array name to another makes them refer to the same array, and the == operator checks for identical references rather than identical element values.
Arrays allow the grouping of multiple values of the same type under a single name. An array is declared with a base type and size, and individual elements can be accessed via an index. Arrays are useful for organizing related data and can be passed to methods. Common array operations include initialization, accessing elements, searching, and sorting. Multidimensional arrays extend the concept to multiple indices.
Arrays allow the grouping of multiple values of the same type under a single name. An array is declared with a base type and size, and individual elements can be accessed via an index. Arrays are useful for organizing related data and can be passed to methods. Common array operations include initialization, accessing elements, searching, and sorting. Multidimensional arrays extend the concept to multiple indices.
Arrays allow us to organize multiple values of the same type into a single variable name. An array is declared with a base type and size, such as int[] grades = new int[100]. Individual elements in the array are accessed using an index from 0 to length-1. Arrays can be passed to methods by reference, allowing the method to modify the array elements. Multidimensional arrays organize data into rows and columns and are declared with multiple sets of brackets like int[][] table = new int[10][20].
Engineering CS 5th Sem Python Module -2.pptxhardii0991
This document discusses various Python string manipulation techniques. It covers concatenating and slicing strings, changing string values using indexes, concatenating and replicating lists of strings. It also covers tuples, working with strings, string literals, formatting strings, useful string methods like join(), split(), strip(), and converting between strings and integers.
The document provides an overview of data structures and algorithms. It discusses key topics like:
1) Different types of data structures including primitive, linear, non-linear, and arrays.
2) The importance of algorithms and how to write them using steps, comments, variables, and control structures.
3) Common operations on data structures like insertion, deletion, searching, and sorting.
4) Different looping and selection statements that can be used in algorithms like for, while, and if-then-else.
5) How arrays can be used as a structure to store multiple values in a contiguous block of memory.
Arrays allow the grouping of multiple values of the same type under a single name. An array is declared with a base type and size, and individual elements can be accessed via an index. Arrays are useful for organizing related data and can be passed to methods. Common array operations include initialization, accessing elements, searching, and sorting. Multidimensional arrays extend the concept to multiple indices.
Arrays allow us to organize multiple values of the same type into a single variable name. An array is declared with square brackets containing the number of elements, and individual elements are accessed via an index number. Arrays can be passed as arguments to methods, where the method can modify class-type elements but only sees the value of primitive-type elements. Array names are reference types, so assigning one array name to another makes them refer to the same array, and the == operator checks for identical references rather than identical element values.
Arrays allow the grouping of multiple values of the same type under a single name. An array is declared with a base type and size, and individual elements can be accessed via an index. Arrays are useful for organizing related data and can be passed to methods. Common array operations include initialization, accessing elements, searching, and sorting. Multidimensional arrays extend the concept to multiple indices.
Arrays allow the grouping of multiple values of the same type under a single name. An array is declared with a base type and size, and individual elements can be accessed via an index. Arrays are useful for organizing related data and can be passed to methods. Common array operations include initialization, accessing elements, searching, and sorting. Multidimensional arrays extend the concept to multiple indices.
Arrays allow us to organize multiple values of the same type into a single variable name. An array is declared with a base type and size, such as int[] grades = new int[100]. Individual elements in the array are accessed using an index from 0 to length-1. Arrays can be passed to methods by reference, allowing the method to modify the array elements. Multidimensional arrays organize data into rows and columns and are declared with multiple sets of brackets like int[][] table = new int[10][20].
Engineering CS 5th Sem Python Module -2.pptxhardii0991
This document discusses various Python string manipulation techniques. It covers concatenating and slicing strings, changing string values using indexes, concatenating and replicating lists of strings. It also covers tuples, working with strings, string literals, formatting strings, useful string methods like join(), split(), strip(), and converting between strings and integers.
TypeScript is a superset of JavaScript that compiles to plain JavaScript code. It introduces additional syntax like interfaces, classes, and modules to JavaScript. TypeScript files use the .ts extension and are compiled to JavaScript using a TypeScript compiler. TypeScript supports basic data types like numbers, strings, booleans, arrays, enums, tuples, and objects. Functions and parameters can be defined with optional types in TypeScript.
Strings in Python are sequence of characters that are immutable. They can be indexed, sliced, concatenated and their cases can be changed. Common string methods include find, count, strip, replace, capitalize etc. Lists are mutable sequences that can contain elements of different types. Common list operations include append, insert, pop, remove, sort etc. Tuples are immutable sequences that can be nested and support operations like slicing, indexing, unpacking etc. Sets are unordered collections of unique elements that support membership testing and set operations. Dictionaries are mutable mappings of unique keys to values that support various operations like get, update, keys, values etc.
CS4443 - Modern Programming Language - I Lecture (2)Dilawar Khan
Topic Covered:
================================================
Basic Data Types and their Mapping to CTS
Variables, Constants, and Operators
Working with Flow Control and Conditional Statements
Type Conversion, String Manipulation and Complex Variable Types
Arrays in C#
foreach loop
The document defines and describes different types of arrays in C programming. It states that arrays can hold multiple values of the same data type and are used to store data in linear or tabular form. The key types discussed are one-dimensional, two-dimensional, and multi-dimensional arrays. It provides examples and explains how to declare, initialize, search and sort each array type.
This document discusses data structures and algorithms. It provides course objectives which include imparting concepts of data structures and algorithms, introducing searching and sorting techniques, and developing applications using suitable data structures. Course outcomes include understanding algorithm performance analysis, concepts of data structures, linear data structures, and identifying efficient data structure implementations. The document also covers algorithm basics, specifications, expressions, analysis techniques and asymptotic notations for analyzing algorithms.
Kotlin is a programming language that can be used for Android development. It is interoperable with Java and compiles to JVM bytecode. Some key features of Kotlin discussed in the document include null safety, properties, functions, classes, inheritance, and Android integration. Kotlin code can inherit from and call Java code, and most Android APIs are written in Java so they can be called from Kotlin as well. The document provides examples of Kotlin syntax for variables, control flow, collections, and comparing Kotlin and Java implementations of common patterns like fragments. References are also included for further Kotlin learning resources.
This document discusses Python data types and variables. It covers numeric data types like int and float, as well as Boolean, string, and sequence data types. It also defines what a variable is, how to name variables, and how to print and update variable values. It introduces type casting and the input function for getting user input.
Unit I - 1R introduction to R program.pptxSreeLaya9
This document provides an introduction to R programming. It discusses basic interactions with R, using R as a calculator, vectors, factors, data frames, missing values, functions, packages, and data pipelines. R can be used for statistical analysis, data visualization, and machine learning. Key functions and objects discussed include reading and writing data, data frames, factors, vectors, user-defined and built-in functions, and the pipe operator.
The document discusses various topics in Python programming including literal constants, numbers, strings, variables, data types, operators, and expressions. It defines literal constants as values that cannot be changed and lists examples. It describes the different number types in Python and issues with floating point numbers. It also covers formatting numbers, simple numeric operations, strings, variable naming rules, data types, assigning values, comments, and indentation in Python code.
an introduction to c++ templates-comprehensive guide.pptAbdullah Yousafzai
This document discusses generic programming in C++ using templates. It provides motivation for generic programming by describing limitations of procedural and object-oriented programming alone. Templates allow functions and classes to be parameterized by type, enabling code reuse. The C++ Standard Template Library (STL) is used as an example, with algorithms operating independently of data types through iterators and callable objects. Templates introduce both type parameterization and interface polymorphism, allowing code to work with any types that meet template requirements.
Arrays are a collection of elements of the same type stored in contiguous memory locations. One-dimensional arrays store elements in a list, accessed by index. Multi-dimensional arrays arrange elements in multiple dimensions, accessed by multiple indices. Array indices must be non-negative integers less than the array size. Arrays are passed by reference to functions. Parallel arrays hold related data. Strings in C++ are null-terminated character arrays.
Python is an interpreted, general-purpose, high-level programming language. It allows programmers to define functions for reusing code and scoping variables within functions. Key concepts covered include objects, expressions, conditionals, loops, modules, files, and recursion. Functions can call other functions, allowing for modular and reusable code.
This document summarizes key concepts from Chapter 2 of a Computer Programming I course, including:
- The structure of a Java program and how to save, compile, and run Java files.
- Using variables to store and represent data in Java, including data types, naming conventions, and assignment statements.
- How to select the proper data types for numerical variables and initialize variables.
- Using simple keyboard input and screen output in Java programs.
Values in Python can belong to different data types including numbers, strings, and lists. Numbers include integers, floating point numbers, and complex numbers. Strings are a sequence of characters that can be defined using single quotes, double quotes, or triple quotes. Common data types in Python include numbers, strings, lists, tuples, and dictionaries. Lists are mutable sequences while tuples are immutable sequences.
This presentation of ROBO INDIA comprises all of the elements that must be known to learn the programming language C.
This ppt also explains all these topics in details.
We welcome all you views and queries. Please write us, we are found at-
website: http://roboindia.com
mail: info@roboindia.com
This document provides a summary of different data types in C programming language. It discusses basic data types like integer, floating point, character and void. It also explains derived data types like pointers, arrays, structures, unions and functions. For each data type, it provides the declaration syntax and examples to illustrate how they are used to declare variables of different types in C.
Leadership Ambassador club Adventist modulekakomaeric00
Aims to equip people who aspire to become leaders with good qualities,and with Christian values and morals as per Biblical teachings.The you who aspire to be leaders should first read and understand what the ambassador module for leadership says about leadership and marry that to what the bible says.Christians sh
TypeScript is a superset of JavaScript that compiles to plain JavaScript code. It introduces additional syntax like interfaces, classes, and modules to JavaScript. TypeScript files use the .ts extension and are compiled to JavaScript using a TypeScript compiler. TypeScript supports basic data types like numbers, strings, booleans, arrays, enums, tuples, and objects. Functions and parameters can be defined with optional types in TypeScript.
Strings in Python are sequence of characters that are immutable. They can be indexed, sliced, concatenated and their cases can be changed. Common string methods include find, count, strip, replace, capitalize etc. Lists are mutable sequences that can contain elements of different types. Common list operations include append, insert, pop, remove, sort etc. Tuples are immutable sequences that can be nested and support operations like slicing, indexing, unpacking etc. Sets are unordered collections of unique elements that support membership testing and set operations. Dictionaries are mutable mappings of unique keys to values that support various operations like get, update, keys, values etc.
CS4443 - Modern Programming Language - I Lecture (2)Dilawar Khan
Topic Covered:
================================================
Basic Data Types and their Mapping to CTS
Variables, Constants, and Operators
Working with Flow Control and Conditional Statements
Type Conversion, String Manipulation and Complex Variable Types
Arrays in C#
foreach loop
The document defines and describes different types of arrays in C programming. It states that arrays can hold multiple values of the same data type and are used to store data in linear or tabular form. The key types discussed are one-dimensional, two-dimensional, and multi-dimensional arrays. It provides examples and explains how to declare, initialize, search and sort each array type.
This document discusses data structures and algorithms. It provides course objectives which include imparting concepts of data structures and algorithms, introducing searching and sorting techniques, and developing applications using suitable data structures. Course outcomes include understanding algorithm performance analysis, concepts of data structures, linear data structures, and identifying efficient data structure implementations. The document also covers algorithm basics, specifications, expressions, analysis techniques and asymptotic notations for analyzing algorithms.
Kotlin is a programming language that can be used for Android development. It is interoperable with Java and compiles to JVM bytecode. Some key features of Kotlin discussed in the document include null safety, properties, functions, classes, inheritance, and Android integration. Kotlin code can inherit from and call Java code, and most Android APIs are written in Java so they can be called from Kotlin as well. The document provides examples of Kotlin syntax for variables, control flow, collections, and comparing Kotlin and Java implementations of common patterns like fragments. References are also included for further Kotlin learning resources.
This document discusses Python data types and variables. It covers numeric data types like int and float, as well as Boolean, string, and sequence data types. It also defines what a variable is, how to name variables, and how to print and update variable values. It introduces type casting and the input function for getting user input.
Unit I - 1R introduction to R program.pptxSreeLaya9
This document provides an introduction to R programming. It discusses basic interactions with R, using R as a calculator, vectors, factors, data frames, missing values, functions, packages, and data pipelines. R can be used for statistical analysis, data visualization, and machine learning. Key functions and objects discussed include reading and writing data, data frames, factors, vectors, user-defined and built-in functions, and the pipe operator.
The document discusses various topics in Python programming including literal constants, numbers, strings, variables, data types, operators, and expressions. It defines literal constants as values that cannot be changed and lists examples. It describes the different number types in Python and issues with floating point numbers. It also covers formatting numbers, simple numeric operations, strings, variable naming rules, data types, assigning values, comments, and indentation in Python code.
an introduction to c++ templates-comprehensive guide.pptAbdullah Yousafzai
This document discusses generic programming in C++ using templates. It provides motivation for generic programming by describing limitations of procedural and object-oriented programming alone. Templates allow functions and classes to be parameterized by type, enabling code reuse. The C++ Standard Template Library (STL) is used as an example, with algorithms operating independently of data types through iterators and callable objects. Templates introduce both type parameterization and interface polymorphism, allowing code to work with any types that meet template requirements.
Arrays are a collection of elements of the same type stored in contiguous memory locations. One-dimensional arrays store elements in a list, accessed by index. Multi-dimensional arrays arrange elements in multiple dimensions, accessed by multiple indices. Array indices must be non-negative integers less than the array size. Arrays are passed by reference to functions. Parallel arrays hold related data. Strings in C++ are null-terminated character arrays.
Python is an interpreted, general-purpose, high-level programming language. It allows programmers to define functions for reusing code and scoping variables within functions. Key concepts covered include objects, expressions, conditionals, loops, modules, files, and recursion. Functions can call other functions, allowing for modular and reusable code.
This document summarizes key concepts from Chapter 2 of a Computer Programming I course, including:
- The structure of a Java program and how to save, compile, and run Java files.
- Using variables to store and represent data in Java, including data types, naming conventions, and assignment statements.
- How to select the proper data types for numerical variables and initialize variables.
- Using simple keyboard input and screen output in Java programs.
Values in Python can belong to different data types including numbers, strings, and lists. Numbers include integers, floating point numbers, and complex numbers. Strings are a sequence of characters that can be defined using single quotes, double quotes, or triple quotes. Common data types in Python include numbers, strings, lists, tuples, and dictionaries. Lists are mutable sequences while tuples are immutable sequences.
This presentation of ROBO INDIA comprises all of the elements that must be known to learn the programming language C.
This ppt also explains all these topics in details.
We welcome all you views and queries. Please write us, we are found at-
website: http://roboindia.com
mail: info@roboindia.com
This document provides a summary of different data types in C programming language. It discusses basic data types like integer, floating point, character and void. It also explains derived data types like pointers, arrays, structures, unions and functions. For each data type, it provides the declaration syntax and examples to illustrate how they are used to declare variables of different types in C.
Leadership Ambassador club Adventist modulekakomaeric00
Aims to equip people who aspire to become leaders with good qualities,and with Christian values and morals as per Biblical teachings.The you who aspire to be leaders should first read and understand what the ambassador module for leadership says about leadership and marry that to what the bible says.Christians sh
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?NWEXAM
Begin Your Preparation Here: https://bit.ly/3VfYStG — Access comprehensive details on the FCP_FAC_AD-6.5 exam guide and excel in the Fortinet Certified Professional - Network Security certification. Gather all essential information including tutorials, practice tests, books, study materials, exam questions, and the syllabus. Solidify your knowledge of Fortinet FCP_FAC_AD-6.5 certification. Discover everything about the FCP_FAC_AD-6.5 exam, including the number of questions, passing percentage, and the time allotted to complete the test.
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...dsnow9802
Jill Pizzola's tenure as Senior Talent Acquisition Partner at THOMSON REUTERS in Marlton, New Jersey, from 2018 to 2023, was marked by innovation and excellence.
A Guide to a Winning Interview June 2024Bruce Bennett
This webinar is an in-depth review of the interview process. Preparation is a key element to acing an interview. Learn the best approaches from the initial phone screen to the face-to-face meeting with the hiring manager. You will hear great answers to several standard questions, including the dreaded “Tell Me About Yourself”.
IT Career Hacks Navigate the Tech Jungle with a RoadmapBase Camp
Feeling overwhelmed by IT options? This presentation unlocks your personalized roadmap! Learn key skills, explore career paths & build your IT dream job strategy. Visit now & navigate the tech world with confidence! Visit https://www.basecamp.com.sg for more details.
Job Finding Apps Everything You Need to Know in 2024SnapJob
SnapJob is revolutionizing the way people connect with work opportunities and find talented professionals for their projects. Find your dream job with ease using the best job finding apps. Discover top-rated apps that connect you with employers, provide personalized job recommendations, and streamline the application process. Explore features, ratings, and reviews to find the app that suits your needs and helps you land your next opportunity.
Joyce M Sullivan, Founder & CEO of SocMediaFin, Inc. shares her "Five Questions - The Story of You", "Reflections - What Matters to You?" and "The Three Circle Exercise" to guide those evaluating what their next move may be in their careers.
5 Common Mistakes to Avoid During the Job Application Process.pdfAlliance Jobs
The journey toward landing your dream job can be both exhilarating and nerve-wracking. As you navigate through the intricate web of job applications, interviews, and follow-ups, it’s crucial to steer clear of common pitfalls that could hinder your chances. Let’s delve into some of the most frequent mistakes applicants make during the job application process and explore how you can sidestep them. Plus, we’ll highlight how Alliance Job Search can enhance your local job hunt.
1. C++ Programming:
Program Design Including
Data Structures, Third Edition
Chapter 8: User-Defined Simple Data
Types, Namespaces, and the string Type
2. Objectives
In this chapter you will:
• Learn how to create and manipulate your own
simple data type—called the enumeration
type
• Become aware of the typedef statement
• Learn about the namespace mechanism
• Explore the string data type, and learn how to
use the various string functions to manipulate
strings
3. Enumeration Type
• Data type - a set of values together with a set
of operations on those values
• To define a new simple data type, called
enumeration type, we need three things:
− A name for the data type
− A set of values for the data type
− A set of operations on the values
4. Enumeration Type (continued)
• A new simple data type can be defined by
specifying its name and the values, but not
the operations
• The values must be identifiers
5. Enumeration Type (continued)
• The syntax for enumeration type is:
• value1, value2, … are identifiers called
enumerators
• value1 < value2 < value3 <...
6. Enumeration Type (continued)
• Enumeration type is an ordered set of values
• If a value has been used in one enumeration
type
− It cannot be used by another in the same
block
• The same rules apply to enumeration types
declared outside of any blocks
7.
8.
9.
10. Assignment
• The statement:
popularSport = FOOTBALL;
stores the word FOOTBALL into
popularSport
• The statement:
mySport = popularSport;
copies the contents of the variable
popularSport into mySport
11. Operations
• No arithmetic operation is allowed on
enumeration types
• The following statements are illegal:
12. Operations (continued)
• The increment and decrement operations are
not allowed on enumeration types
• The following statements are illegal:
14. Operations and Input/Output
• Because an enumeration is an ordered set of
values
− We can use relational operators with them
• The cast operator can be used to increment,
decrement, and compare values
− Values can be used in loops
• Input and output are defined only for built-in data
types such as int, char, double
• The enumeration type can be neither input nor
output (directly)
15. Functions and Enumeration Types
• Enumeration type can be passed as
parameters to functions either by value or by
reference
• A function can return a value of the
enumeration type
16. Anonymous Data Types
• Anonymous - a data type in which values are
directly specified in the variable declaration
with no type name, for example:
• Creating an anonymous type has drawbacks
• We cannot pass an anonymous type as a
parameter to a function
17. Anonymous Data Types
(continued)
• A function cannot return a value of an
anonymous type
• Values used in one can be used in another,
but they are treated differently
18. typedef Statement
• You can create synonyms or aliases to a
previously defined data type by using the
typedef statement
• The syntax of the typedef statement is:
• typedef does not create any new data types
• typedef creates an alias to an existing data
type
19. ANSI/ISO Standard C++
• ANSI/ISO standard C++ was officially
approved in July 1998
• Most of the recent compilers are also
compatible with ANSI/ISO standard C++
• For the most part, standard C++ and ANSI/ISO
standard C++ are the same, but
− ANSI/ISO Standard C++ has some features not
available in Standard C++
20. Namespaces
• When a header file, such as iostream, is
included in a program
− Global identifiers in the header file also
become global identifiers in the program
• If a global identifier in a program has the
same name as one of the global identifiers in
the header file
− The compiler will generate a syntax error
(such as identifier redefined)
• The same problem can occur if a program
uses third party libraries
21. Namespaces (continued)
• To overcome this problem, third party
vendors begin their global identifiers with a
special symbol
• Because compiler vendors begin their global
identifier with _ (underscore)
− To avoid linking errors, do not begin identifiers
in your program with _
• ANSI/ISO standard C++ attempts to solve this
problem of overlapping global identifier
names with the namespace mechanism
22. Syntax: namespace
• The syntax of the statement namespace is:
where a member is usually a variable
declaration, a named constant, a function, or
another namespace
23.
24. Accessing a namespace Member
• The scope of a namespace member is local
to the namespace
• Usually two ways a namespace member can
be accessed outside the namespace
• One way is to use the syntax:
namespace_name::identifier
• To access the member rate of the
namespace globalType, the following
statement is required:
globalType::RATE
25. Accessing a namespace Member
(continued)
• To access the function printResult, the
following statement is required:
globalType::printResult();
• To simplify the accessing of all namespace
members:
using namespace namespace_name;
• To simplify the accessing of a specific
namespace member:
using namespace_name::identifier;
26. The using Statement
• After the using statement
− Not necessary to precede the
namespace_name and the scope resolution
operator before the namespace member
• If a namespace member and a global
identifier or a block identifier have the same
name
− namespace_name and scope resolution
operator must precede the namespace
member
27. The string Type
• To use the data type string, the program
must include the header file <string>
• The statement
string name = "William Jacob";
declares name to be a string variable and
also initializes name to "William Jacob"
• The first character in name, 'W', is in position
0, the second character, 'i', is in position 1,
and so on
28. The string Type (continued)
• The variable name is capable of storing any
size string
• Binary operator + (to allow the string
concatenation operation), and the array
subscript operator [], have been defined for
the data type string
• For example, if str1 = "Sunny", the
statement stores the string "Sunny Day" into
str2:
str2 = str1 + " Day";
29. length Function
• Length returns the number of characters
currently in the string
• The syntax to call the length function is:
strVar.length()
where strVar is variable of the type string
• length has no arguments
• length returns an unsigned integer
• The value returned can be stored in an integer
variable
30.
31. size Function
• The function size is the same as the function
length
• Both functions return the same value
• The syntax to call the function size is:
strVar.size()
where strVar is variable of the type string
• As in the case of the function length, the
function size has no arguments
32. find Function
• find searches a string for the first occurrence of
a particular substring
• Returns an unsigned integer value of type
string::size_type giving the result of the
search
• The syntax to call the function find is:
strVar.find(strExp)
where strVar is a string variable and strExp
is a string expression evaluating to a string
• The string expression strExp can also be a
character
33. find Function (continued)
• If successful, find returns the position in
strVar where the match begins
• For the search to be successful, the match
must be exact
• If unsuccessful, find returns the special value
string::npos (“not a position within the
string”)
34.
35. substr Function
• substr returns a particular substring of a
string
• The syntax to call the function substr is:
strVar.substr(expr1,expr2)
where expr1 and expr2 are expressions
evaluating to unsigned integers
36. substr Function (continued)
• The expression expr1 specifies a position
within the string (starting position of the
substring)
• The expression expr2 specifies the length of
the substring to be returned
37.
38. swap Function
• swap interchanges the contents of two string
variables
• The syntax to use the function swap is
strVar1.swap(strVar2);
where strVar1 and strVar2 are string
variables
• Suppose you have the following statements:
string str1 = "Warm";
string str2 = "Cold";
• After str1.swap(str2); executes, the
value of str1 is "Cold" and the value of
str2 is "War
39. Programming Example: Pig Latin
Strings
• Program prompts user to input a string
− Then outputs the string in the pig Latin form
• The rules for converting a string into pig
Latin form are as follows:
1. If the string begins with a vowel, add the
string "-way" at the end of the string
− For example, the pig Latin form of the string
"eye" is "eye-way"
40. Pig Latin Strings (continued)
2. If the string does not begin with a vowel, first
add "-" at the end of the string
− Then move the first character of the string to
the end of the string until the first character of
the string becomes a vowel
− Next, add the string "ay" at the end
− For example, the pig Latin form of the string
"There" is "ere-Thay"
41. Pig Latin Strings (continued)
3. Strings such as "by" contain no vowels
− In cases like this, the letter y can be considered
a vowel
− For this program, the vowels are a, e, i, o, u,
y, A, E, I, O, U, and Y; the pig Latin form of
"by" is "y-bay"
4. Strings such as "1234" contain no vowels
− The pig Latin form of a string that has no vowels
in it is the string followed by the string "-way"
− For example, the pig Latin form of the string
"1234" is "1234-way"
42. Problem Analysis
• If str denotes a string
− Check the first character, str[0], of str
− If str[0] is a vowel, add "-way" at the end of str
− If the first character of str, str[0], is not a vowel
• First add "-" at the end of the string
• Remove the first character of str from str and put
it at end of str
• Now the second character of str becomes the first
character of str
43. Problem Analysis (continued)
− This process is repeated until either
• The first character of str is a vowel
• All characters of str are processed, in which
case str does not contain any vowels
44. Algorithm Design
• The program contains the following functions:
− isVowel - to determine whether a character is a vowel
− rotate - to move first character of str to the end of
str
− pigLatinString - to find the pig Latin form of str
• Steps in the Algorithm:
1. Get str
2. Use the function pigLatinString to find the pig
Latin form of str
3. Output the pig Latin form of str
45.
46. Function rotate
• Takes a string as a parameter
• Removes the first character of the string
− Places it at end of the string by extracting the
substring starting at position 1 until the end of
the string, and then adding the first character of
the string
48. Function pigLatinString
• If pStr[0] is a vowel, add "-way" at end of pStr
• If pStr[0] is not a vowel
− Move the first character of pStr to the end of pStr
− The second character of pStr becomes the first character of
pStr
• Now pStr may or may not contain a vowel
− Use a bool variable, foundVowel, which is set to true if
pStr contains a vowel, and false otherwise
− Initialize foundVowel to false
49. Function pigLatinString
(continued)
− if pStr[0] is not a vowel, move str[0] to
the end of pStr by calling the function rotate
− Repeat third step until either the first character
of pStr becomes a vowel or all characters of
pStr have been checked
• Convert pStr into the pig Latin form
• Return pStr
50. Main Algorithm
1. Get the string
2. Call the function pigLatinString to find
the pig Latin form of the string
3. Output the pig Latin form of the string
51. Summary
• An enumeration type is a set of ordered
values
• Reserved word enum creates an enumeration
type
• No arithmetic operations are allowed on the
enumeration type
• Relational operators can be used with enum
values
• Enumeration type values cannot be input or
output directly
52. Summary (continued)
• An anonymous type is one where a variable’s
values are specified without any type name
• C++’s reserved word typedef creates
synonyms or aliases to previously defined
data types
• The namespace mechanism is a feature of
ANSI/ISO Standard C++
• A namespace member is usually a named
constant, variable, function, or another
namespace
53. Summary (continued)
• The keyword namespace must appear in the
using statement
• A string is a sequence of zero or more
characters
• Strings in C++ are enclosed in double
quotation marks
• In C++, [] is called the array subscript
operator
• The function length returns the number of
characters currently in the string
54. Summary (continued)
• The function size returns the number of
characters currently in the string
• The function find searches a string to locate
the first occurrence of a particular substring
• The function substr returns a particular
substring of a string
• The function swap is used to swap the
contents of two string variables