The document outlines the key topics covered in Chapter 15 on strings and characters in C#, including fundamentals of characters and strings, string constructors, using the string indexer and length property, comparing strings, and using methods like StartsWith and EndsWith. Code examples are provided to demonstrate using features like the string indexer, Length property, CopyTo method, comparing strings with Equals and CompareTo, and checking if a string starts or ends with a substring.
The document discusses object-oriented programming concepts like polymorphism. It includes:
- An introduction to polymorphism and how it allows programs to handle related classes generically and be easily extensible.
- Examples of polymorphism including a shape hierarchy with classes like Quadrilateral, Rectangle, etc. and a space object hierarchy with classes that all implement a DrawYourself method.
- Details about abstract classes and how they provide base classes that concrete classes inherit from while requiring the concrete classes to implement abstract methods and properties.
- A case study demonstrating inheritance and polymorphism using abstract base class Shape and concrete classes Point2, Circle2, and Cylinder2 that inherit from Shape.
The document outlines control structures in programming, including counter-controlled repetition, the for loop structure, the switch multiple-selection structure, and the do/while repetition structure. It provides code examples to demonstrate these structures, including initializing and incrementing counters, using break and continue statements to alter loop flow, and displaying output.
The document discusses various graphical user interface controls in C#, including menus, link labels, list boxes, combo boxes, tree views, and tab controls. It provides code examples to demonstrate how to implement menus with options to change font colors and styles, as well as link labels that link to other programs or files when clicked. Event handlers are used to handle user interactions with the controls.
The document discusses graphics and media capabilities in .NET, including graphics contexts, colors, fonts, and images. It covers creating graphics objects, setting colors using RGB values or names, constructing fonts and accessing font metrics, and loading/displaying images. Code examples are provided to demonstrate these graphics and font capabilities.
The document describes object-oriented programming concepts like classes, objects, encapsulation, and properties. It provides code examples of a Time class that encapsulates time data and provides methods to work with it. The Time class uses properties to safely access private member variables for hour, minute and second. Constructors are demonstrated that initialize Time objects with different parameters.
This document discusses exception handling in .NET. It defines exceptions as objects that are thrown when errors or unexpected events occur during program execution. Exceptions allow errors to be handled at multiple levels through try-catch blocks. The core exception class is System.Exception, which other custom exceptions inherit from. Exceptions can be thrown manually with throw or occur automatically from errors. Finally blocks ensure code is always executed even if an exception is thrown.
03. Operators Expressions and statementsIntro C# Book
In this chapter we will get acquainted with the operators in C# and the actions they can perform on the different data types. We will explain the priorities of the operators and we will analyze the different types of operators, according to the count of the arguments they can take and the actions they can perform. In the second part we will examine the conversion of data types. We will explain when and why it is needed to be done and how to work with different data types. At the end of the chapter we will pay special attention to the expressions and how we should work with them.
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
Introduction to looping, for loop. while loop, do loop jump statements, entry controlled vs exit controlled loop, algorithm and flowchart of loops, factorial of a number
The document discusses object-oriented programming concepts like polymorphism. It includes:
- An introduction to polymorphism and how it allows programs to handle related classes generically and be easily extensible.
- Examples of polymorphism including a shape hierarchy with classes like Quadrilateral, Rectangle, etc. and a space object hierarchy with classes that all implement a DrawYourself method.
- Details about abstract classes and how they provide base classes that concrete classes inherit from while requiring the concrete classes to implement abstract methods and properties.
- A case study demonstrating inheritance and polymorphism using abstract base class Shape and concrete classes Point2, Circle2, and Cylinder2 that inherit from Shape.
The document outlines control structures in programming, including counter-controlled repetition, the for loop structure, the switch multiple-selection structure, and the do/while repetition structure. It provides code examples to demonstrate these structures, including initializing and incrementing counters, using break and continue statements to alter loop flow, and displaying output.
The document discusses various graphical user interface controls in C#, including menus, link labels, list boxes, combo boxes, tree views, and tab controls. It provides code examples to demonstrate how to implement menus with options to change font colors and styles, as well as link labels that link to other programs or files when clicked. Event handlers are used to handle user interactions with the controls.
The document discusses graphics and media capabilities in .NET, including graphics contexts, colors, fonts, and images. It covers creating graphics objects, setting colors using RGB values or names, constructing fonts and accessing font metrics, and loading/displaying images. Code examples are provided to demonstrate these graphics and font capabilities.
The document describes object-oriented programming concepts like classes, objects, encapsulation, and properties. It provides code examples of a Time class that encapsulates time data and provides methods to work with it. The Time class uses properties to safely access private member variables for hour, minute and second. Constructors are demonstrated that initialize Time objects with different parameters.
This document discusses exception handling in .NET. It defines exceptions as objects that are thrown when errors or unexpected events occur during program execution. Exceptions allow errors to be handled at multiple levels through try-catch blocks. The core exception class is System.Exception, which other custom exceptions inherit from. Exceptions can be thrown manually with throw or occur automatically from errors. Finally blocks ensure code is always executed even if an exception is thrown.
03. Operators Expressions and statementsIntro C# Book
In this chapter we will get acquainted with the operators in C# and the actions they can perform on the different data types. We will explain the priorities of the operators and we will analyze the different types of operators, according to the count of the arguments they can take and the actions they can perform. In the second part we will examine the conversion of data types. We will explain when and why it is needed to be done and how to work with different data types. At the end of the chapter we will pay special attention to the expressions and how we should work with them.
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
Introduction to looping, for loop. while loop, do loop jump statements, entry controlled vs exit controlled loop, algorithm and flowchart of loops, factorial of a number
This document discusses control flow and control structures in programming, including conditional structures like if/else statements and repetition structures like while and for loops.
It provides examples of simple if statements, if/else statements, if/elif/else statements, and nested if statements. It also discusses indefinite loops with while and definite loops with for, and how to break and continue loops.
Finally, it covers pass and return statements, local and global scopes, function composition, lambda functions, string slicing, string methods, and that strings are immutable in Python.
In this chapter we will cover the conditional statements in C#, which we can use to execute different actions depending on a given condition. We will explain the syntax of the conditional operators if and if-else with suitable examples and explain the practical application of the operator for selection switch-case.
The document describes how a while loop works in Python. It uses an example of a program that prints numbers from 1 to 4 using a while loop. The while loop initializes a variable x as 1, then checks if x is less than 5, prints x, and increments x by 1 each iteration, repeating until the condition x < 5 is no longer true when x becomes 5.
The document provides an overview of the C++ programming language. It discusses what C++ is, its history and features. It then outlines various C++ concepts like identifiers, constants, data types, comments, operators, variables, and statements. It also covers control structures like decision making statements (if-else, switch), looping (for, while, do-while), and functions. The document is intended as a lecture on the basic elements of the C++ language.
The document outlines a chapter on methods in C#. It discusses key concepts like defining methods, passing arguments by value vs reference, and using built-in classes like Math. It provides examples of methods that square integers, find the maximum of 3 numbers, and demonstrate passing by reference and out parameters.
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
The document provides information about various Python concepts like print statement, variables, data types, operators, conditional statements, loops, functions, modules, exceptions, files and packages. It explains print statement syntax, how variables work in Python, built-in data types like numbers, strings, lists, dictionaries and tuples. It also discusses conditional statements like if-else, loops like while and for, functions, modules, exceptions, file handling operations and packages in Python.
The Triangle class lab involves creating a Triangle class that defines properties and methods for triangles. The Triangle class contains private data members for the three sides of the triangle. It includes public methods to calculate the area and perimeter of a triangle using the side lengths, get the side lengths, set the side lengths, determine the triangle type, and print triangle information. The main() function constructs a Triangle object and calls its methods to demonstrate the class functionality in 3 sentences or less.
In this chapter we will get familiar with the console as a tool for data input and output. We will explain what it is, when and how to use it, and how most programming languages access the console. We will get familiar with some of the features in C# for user interaction: reading text and numbers from the console and printing text and numbers. We will also examine the main streams for input-output operations Console.In, Console.Out and Console.Error, the Console and the usage of format strings for printing data in various formats.
In this chapter we will get more familiar with what methods are and why we need to use them. The reader will be shown how to declare methods, what parameters are and what a method’s signature is, how to call a method, how to pass arguments of methods and how methods return values. At the end of this chapter we will know how to create our own method and how to use (invoke) it whenever necessary. Eventually, we will suggest some good practices in working with methods. The content of this chapter accompanied by detailed examples and exercises that will help the reader practice the learned material.
This document discusses arrays and pointers in C++. It begins by explaining that arrays allow storing multiple values of the same type, and that arrays have a fixed size and type after declaration. It then covers how to declare, initialize, access elements of, and iterate through arrays using indexes and loops. Multidimensional arrays are also explained, including how they can be thought of as tables with rows and columns. The document concludes by introducing pointers as variables that store the memory addresses of other variables.
The document provides information about arrays and pointers in C++. It discusses how to declare, initialize, access elements of arrays including multi-dimensional arrays. It also covers pointers, how they store memory addresses rather than values, and how to declare and assign addresses to pointers. Key topics include declaring arrays with syntax like dataType arrayName[size]; initializing arrays; accessing elements using indices; multi-dimensional arrays of different sizes; declaring pointers with syntax like int* pointer; and assigning addresses to pointers using &operator.
This document discusses different types of functions in C++, including user-defined functions, library functions, function parameters, return values, function prototypes, and function overloading. It provides examples to illustrate key concepts like defining functions with different parameters and return types, passing arguments to functions, and returning values from functions. Storage classes like local, global, static local and register variables are also briefly covered. The document is an introduction to functions in C++ programming.
The document discusses control statements in C++, specifically if, if-else, and nested if-else statements. It provides examples of using these conditional statements to evaluate conditions and execute code blocks accordingly. Key topics covered include using if statements to check conditions and run code, if-else statements to choose between two code blocks based on a condition being true or false, and nested if-else statements to evaluate multiple conditions in sequence. The for loop is also introduced as a way to repeat code a set number of times in C++.
The document discusses different types of storage classes in C++ that determine the lifetime and scope of variables:
1. Local variables are defined inside functions and have scope limited to that function. They are destroyed when the function exits.
2. Global variables are defined outside all functions and have scope in the entire program. They are destroyed when the program ends.
3. Static local variables are local variables that retain their value between function calls. Register variables are local variables stored in processor registers for faster access.
4. Thread local storage allows defining variables that are local to each thread and retain their values similar to static variables. The document provides examples to illustrate local, global, and static variables.
This chapter discusses data types in C++. It covers integer types like int and char that store whole numbers and single characters respectively. Floating-point types like float and double are also discussed, which can store fractional numbers. The chapter also covers declarations and defining variables, arithmetic operators, and common programming errors related to data types.
The document provides an overview of computers, operating systems, programming languages, the internet, and Microsoft .NET. It discusses the evolution of computers from early mainframes to personal computers and networks. It covers the development of operating systems, languages like C, C++, Java and C#, and web technologies like HTML, XML and the World Wide Web. It also summarizes Microsoft's .NET framework and how it allows applications to be developed in any .NET compatible language and run across platforms using the Common Language Runtime.
This document discusses control flow and control structures in programming, including conditional structures like if/else statements and repetition structures like while and for loops.
It provides examples of simple if statements, if/else statements, if/elif/else statements, and nested if statements. It also discusses indefinite loops with while and definite loops with for, and how to break and continue loops.
Finally, it covers pass and return statements, local and global scopes, function composition, lambda functions, string slicing, string methods, and that strings are immutable in Python.
In this chapter we will cover the conditional statements in C#, which we can use to execute different actions depending on a given condition. We will explain the syntax of the conditional operators if and if-else with suitable examples and explain the practical application of the operator for selection switch-case.
The document describes how a while loop works in Python. It uses an example of a program that prints numbers from 1 to 4 using a while loop. The while loop initializes a variable x as 1, then checks if x is less than 5, prints x, and increments x by 1 each iteration, repeating until the condition x < 5 is no longer true when x becomes 5.
The document provides an overview of the C++ programming language. It discusses what C++ is, its history and features. It then outlines various C++ concepts like identifiers, constants, data types, comments, operators, variables, and statements. It also covers control structures like decision making statements (if-else, switch), looping (for, while, do-while), and functions. The document is intended as a lecture on the basic elements of the C++ language.
The document outlines a chapter on methods in C#. It discusses key concepts like defining methods, passing arguments by value vs reference, and using built-in classes like Math. It provides examples of methods that square integers, find the maximum of 3 numbers, and demonstrate passing by reference and out parameters.
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
The document provides information about various Python concepts like print statement, variables, data types, operators, conditional statements, loops, functions, modules, exceptions, files and packages. It explains print statement syntax, how variables work in Python, built-in data types like numbers, strings, lists, dictionaries and tuples. It also discusses conditional statements like if-else, loops like while and for, functions, modules, exceptions, file handling operations and packages in Python.
The Triangle class lab involves creating a Triangle class that defines properties and methods for triangles. The Triangle class contains private data members for the three sides of the triangle. It includes public methods to calculate the area and perimeter of a triangle using the side lengths, get the side lengths, set the side lengths, determine the triangle type, and print triangle information. The main() function constructs a Triangle object and calls its methods to demonstrate the class functionality in 3 sentences or less.
In this chapter we will get familiar with the console as a tool for data input and output. We will explain what it is, when and how to use it, and how most programming languages access the console. We will get familiar with some of the features in C# for user interaction: reading text and numbers from the console and printing text and numbers. We will also examine the main streams for input-output operations Console.In, Console.Out and Console.Error, the Console and the usage of format strings for printing data in various formats.
In this chapter we will get more familiar with what methods are and why we need to use them. The reader will be shown how to declare methods, what parameters are and what a method’s signature is, how to call a method, how to pass arguments of methods and how methods return values. At the end of this chapter we will know how to create our own method and how to use (invoke) it whenever necessary. Eventually, we will suggest some good practices in working with methods. The content of this chapter accompanied by detailed examples and exercises that will help the reader practice the learned material.
This document discusses arrays and pointers in C++. It begins by explaining that arrays allow storing multiple values of the same type, and that arrays have a fixed size and type after declaration. It then covers how to declare, initialize, access elements of, and iterate through arrays using indexes and loops. Multidimensional arrays are also explained, including how they can be thought of as tables with rows and columns. The document concludes by introducing pointers as variables that store the memory addresses of other variables.
The document provides information about arrays and pointers in C++. It discusses how to declare, initialize, access elements of arrays including multi-dimensional arrays. It also covers pointers, how they store memory addresses rather than values, and how to declare and assign addresses to pointers. Key topics include declaring arrays with syntax like dataType arrayName[size]; initializing arrays; accessing elements using indices; multi-dimensional arrays of different sizes; declaring pointers with syntax like int* pointer; and assigning addresses to pointers using &operator.
This document discusses different types of functions in C++, including user-defined functions, library functions, function parameters, return values, function prototypes, and function overloading. It provides examples to illustrate key concepts like defining functions with different parameters and return types, passing arguments to functions, and returning values from functions. Storage classes like local, global, static local and register variables are also briefly covered. The document is an introduction to functions in C++ programming.
The document discusses control statements in C++, specifically if, if-else, and nested if-else statements. It provides examples of using these conditional statements to evaluate conditions and execute code blocks accordingly. Key topics covered include using if statements to check conditions and run code, if-else statements to choose between two code blocks based on a condition being true or false, and nested if-else statements to evaluate multiple conditions in sequence. The for loop is also introduced as a way to repeat code a set number of times in C++.
The document discusses different types of storage classes in C++ that determine the lifetime and scope of variables:
1. Local variables are defined inside functions and have scope limited to that function. They are destroyed when the function exits.
2. Global variables are defined outside all functions and have scope in the entire program. They are destroyed when the program ends.
3. Static local variables are local variables that retain their value between function calls. Register variables are local variables stored in processor registers for faster access.
4. Thread local storage allows defining variables that are local to each thread and retain their values similar to static variables. The document provides examples to illustrate local, global, and static variables.
This chapter discusses data types in C++. It covers integer types like int and char that store whole numbers and single characters respectively. Floating-point types like float and double are also discussed, which can store fractional numbers. The chapter also covers declarations and defining variables, arithmetic operators, and common programming errors related to data types.
The document provides an overview of computers, operating systems, programming languages, the internet, and Microsoft .NET. It discusses the evolution of computers from early mainframes to personal computers and networks. It covers the development of operating systems, languages like C, C++, Java and C#, and web technologies like HTML, XML and the World Wide Web. It also summarizes Microsoft's .NET framework and how it allows applications to be developed in any .NET compatible language and run across platforms using the Common Language Runtime.
The document discusses accessibility in web development and software applications. It covers regulations and guidelines for accessibility from the Web Accessibility Initiative (WAI) and other organizations. It also provides examples of implementing accessibility in Visual Studio .NET, C#, XHTML, and Microsoft Windows, including features for visual impairments, hearing impairments, and mobility issues. Specific techniques discussed include adding alt text for images, proper use of headings and structure, keyboard shortcuts, screen reading support, font size adjustments, and more.
This document provides an outline and overview of Chapter 12 which covers graphical user interface (GUI) concepts in Windows Forms. The chapter introduces GUI components like windows, controls, properties, events and event handling. It describes common controls like labels, text boxes, buttons and how to set properties, handle events, and lay out controls on a form. Code examples are provided to demonstrate creating a simple form with a textbox, label and button to display text on a label when a button is clicked.
This document outlines key concepts related to data structures including linked lists, stacks, queues, and trees. It provides code examples of a Node class that is self-referential, allowing objects to link to one another. A LinkedListLibrary class is defined, with methods for inserting and removing nodes from linked lists. A ListTest class tests the functionality of the List class.
The document discusses strings and string manipulation in Java. It covers creating and initializing strings, comparing strings, concatenating strings, searching strings for substrings, extracting substrings, splitting strings, replacing substrings, changing character casing, and using StringBuilder for efficient string modification.
This document provides instructions for writing a C program to count the vowels, consonants, digits, and whitespace in a string. It begins by explaining how to declare, initialize, read, and manipulate strings in C. It then presents the algorithm and full C program to iterate through a string, check each character, and increment the appropriate counter. The program takes a string as input and outputs the count of each type of character. Examples of additional string programs are provided for practice.
The document discusses strings and character arrays in C, including defining and initializing string literals, input and output of strings, common string processing and library functions, validating user input, and formatting output strings. Key topics covered include using gets(), scanf(), and printf() for I/O, comparing and concatenating strings, counting characters and words in a string, and avoiding common errors when working with strings.
This document provides an overview of LINQ (Language Integrated Query) and its capabilities. It introduces LINQ to Objects, LINQ to SQL, and LINQ to XML. LINQ allows developers to query data structures using SQL-like syntax directly in code and integrates with various .NET languages and data sources.
This document outlines Chapter 11 on strings and characters from a 2003 Prentice Hall textbook. It covers the String, StringBuffer, and Character classes, including constructors, methods for length, character access, comparison, searching, and extracting substrings. Code examples demonstrate using various string methods like indexOf, substring, equals, and concatenation.
This document outlines Chapter 11 on strings and characters from a 2003 Prentice Hall textbook. It covers the String, StringBuffer, and Character classes, including constructors, methods for length, character access, comparison, searching, and extracting substrings. Code examples demonstrate using various string methods like indexOf, substring, equals, and concatenation.
This document outlines Chapter 11 from a 2003 Prentice Hall textbook on Strings and Characters in Java. It covers the String, StringBuffer, and Character classes, including constructors, methods for length, comparison, locating/extracting substrings, and concatenation. It also discusses regular expressions and string tokenization. The chapter aims to explain fundamental string processing and manipulation in Java.
The document provides an overview of Strings and StringBuilders in Java. It discusses Strings as immutable objects and how StringBuilders can be more efficient for modifying strings. It also covers common String and StringBuilder methods, when to use each, and exceptions in Java using try/catch blocks.
The document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, functions, and objects. It discusses JavaScript's origins, misunderstandings, dynamic and loosely typed nature, use of prototypes for inheritance rather than classes, and treatment of arrays and objects.
The JavaScript programming language is a multi-paradigm language that is misunderstood due to its name, design errors in early implementations, and use in web browsers. It is a functional language that uses objects, prototypes, and closures. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The JavaScript programming language is a functional language that is commonly misunderstood due to its name, mispositioning, design errors in early implementations, and use in web browsers. It was created in the 1990s and standardized as ECMAScript. JavaScript uses dynamic typing, loose typing, objects as general containers, and prototypal inheritance. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The JavaScript programming language is a multi-paradigm language that is misunderstood due to its name, design errors in early implementations, and use in web browsers. It is a functional language that uses objects, prototypes, and closures. Values in JavaScript include numbers, strings, Booleans, objects, null, and undefined. All other values are objects.
The document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, and objects. It discusses JavaScript's misunderstood nature due to its name, design errors in early implementations, and use in browsers. Some key points made include: JavaScript is a functional language; it uses prototypal inheritance instead of classes; all values are objects except for primitive values; and functions are first-class objects that can be assigned and passed around.
This document provides information about Python and web development. It discusses strings in Python, including creating, accessing, modifying, deleting strings and various string methods and functions. It also provides example problems and code snippets related to string operations in Python.
This document provides an overview of regular expressions (regex) supported by Java's java.util.regex package. It discusses pattern and matcher objects, performing pattern matching, metacharacters, character classes, quantifiers, capturing groups, boundary matchers, and other regex concepts. Key points covered include how patterns are compiled and matched, common metacharacters and predefined character classes, greedy/reluctant/possessive quantifiers, capturing and backreferencing groups, and zero-length matches. Examples are provided to illustrate different regex techniques.
The document discusses C programming concepts like strcpy() function implementation, data types, operators, functions, pointers, arrays, strings and more. It provides code snippets to demonstrate various C programming techniques like implementing string copy functions, converting numbers to different bases, evaluating polynomials, swapping variables, reversing strings, matrix multiplication and more. It also answers questions about common C programming topics to test understanding.
The document discusses strings in C programming language. It provides details about:
- Strings are arrays of characters terminated by a null character '\0'.
- Common functions to declare, initialize, print and manipulate strings like strlen(), strcpy(), strcat(), strcmp() etc.
- Important points about receiving and processing multi-word strings using scanf(), gets() and puts().
- Implementation of some string handling functions like xstrlen(), xstrcpy() to demonstrate their working.
The JavaScript Programming Language document provides an overview of the JavaScript programming language, including its history, key concepts, values, operators, statements, and objects. It notes that JavaScript is a multi-paradigm scripting language that is misunderstood as only for web development. The document outlines JavaScript's core data types, objects, functions, and prototypal inheritance model.
The document discusses the String and StringBuffer classes in Java and their key methods. It covers fundamentals of characters and strings, the various String constructors, methods for comparing and locating substrings in strings, extracting substrings, concatenating strings, and converting between string and character array representations. The StringBuffer class is introduced as a mutable alternative to String for modifying string content. Example code demonstrates the use of many string methods.
Strings are immutable sequences of characters represented by the System.String class in .NET. The document discusses various methods for manipulating strings such as comparing, concatenating, searching, extracting substrings, splitting, replacing, deleting, changing case, and trimming. It recommends using a StringBuilder for efficient modification and building of strings. Formatting strings can be done using the ToString() and String.Format() methods along with formatting placeholders. Parsing numbers and dates from strings is culture-sensitive.
The document discusses accessibility in web development and software applications. It covers topics like web accessibility guidelines, providing alternatives for images, maximizing readability in structures, accessibility in Visual Studio .NET, C#, XHTML tables and frames, and accessibility tools. Code examples are provided to demonstrate making applications more accessible for people with disabilities.
The document discusses client-server networking using both stream sockets and datagrams. It provides code examples for a server and client application that allow text-based communication using stream sockets, establishing a connection between the two. It also gives an example of a connectionless server and client that can send and receive datagrams containing byte arrays to simulate a chat. The server waits for packets and displays the contents, then echoes the data back to the client.
This document outlines a chapter about ASP.NET and web services. It includes code for a web service called HugeInteger that performs operations on large integers. The HugeInteger service exposes methods like Add, Subtract, Bigger etc through SOAP over HTTP. It shows how to publish web services, add service references to projects, and invoke web service methods from a client application.
This chapter discusses ASP.NET web forms and controls. It introduces the system architecture of web applications with different tiers. It then demonstrates creating a simple web form application in Visual Studio that displays the current time using labels and setting properties in the code-behind file. The application is run locally and the generated HTML is shown.
The document outlines how to connect to and query an Access database using ADO.NET in C#. It describes creating a TableDisplay form with a DataGrid to display query results. The form initializes a DataSet and OleDbDataAdapter to retrieve data from the Authors table and bind it to the DataGrid. It also configures OleDbCommands for selecting, inserting, updating, and deleting data.
This document discusses XML and the Document Object Model (DOM). It introduces XML documents and namespaces. It describes how the DOM represents an XML document as a tree structure with parent and child nodes. It provides code examples for reading an XML file using an XmlReader, and manipulating an XML document's DOM tree by building a copy of the tree as TreeNodes in a TreeView control.
The document describes how to search directories and files using the File and Directory classes in C#. It defines a regular expression to match file extensions and stores the number of files found for each extension. The program recursively searches all subdirectories, counts the number of files for each extension, and outputs a summary of the results. It also checks for and allows deleting any backup (.bak) files found.
The document describes multithreading concepts in .NET including thread states, priorities, synchronization, and the producer-consumer relationship. It provides code examples to demonstrate threading without and with synchronization. Key points covered include allowing concurrent execution with threads, thread life cycles and states, using monitors for synchronization, and ensuring proper communication between producer and consumer threads.
This document discusses exception handling in C# and .NET. It provides examples of try/catch blocks, the different exception classes in .NET, and how to access exception properties like Message and StackTrace. Code samples are given that demonstrate throwing, catching, and rethrowing exceptions. Finally blocks are also discussed and shown to always execute even if an exception occurs.
The document discusses object-oriented programming concepts like inheritance, base classes, and derived classes. It provides code examples to illustrate inheritance relationships between classes like Point, Circle, and Cylinder. The code defines base classes like Point and derived classes like Circle that inherit properties and methods from their base classes. Tests are provided to create objects from derived classes and demonstrate inherited functionality.
The document outlines key concepts about arrays including:
- Declaring and allocating arrays
- Initializing arrays with initializer lists or dynamically with 'new'
- Accessing array elements using indexes/subscripts
- Common array operations like totaling elements, creating histograms, and using arrays as counters
It provides code examples demonstrating initializing arrays, summing array elements, creating a histogram to display array data, and using arrays as counters in a dice rolling simulation program.
The document outlines control structures in programming including algorithms, pseudocode, selection structures like if/else, repetition structures like while loops, and case studies applying these concepts. Key topics are counter-controlled and sentinel-controlled repetition for loops, and nesting control structures with if statements inside loops. Examples in C# demonstrate accumulating values in loops and nested if/else statements.
This document outlines the key concepts covered in Chapter 3 of an introduction to C# programming textbook. It discusses simple programs that print text, perform basic math operations, and make decisions using relational operators. Code examples are provided to demonstrate how to write, compile, and run simple C# console applications and use basic programming elements like variables, methods, and conditional statements.
The document provides an overview of the Visual Studio .NET integrated development environment (IDE). It describes the main interface elements like the menu bar, toolbar, solution explorer, toolbox and properties window. It then demonstrates how to create a simple project in Visual Studio .NET that displays text in a label and an image in a picture box without writing any code, using the drag and drop features of the IDE.
The document outlines key concepts about data structures including linked lists, stacks, queues, and trees. It provides code examples for a Node class that is self-referential, allowing objects to link to each other. It also includes a List class that implements basic linked list functionality through methods like InsertAtFront, InsertAtBack, RemoveFromFront, and RemoveFromBack. The code examples demonstrate how to create and manipulate linked lists through a List object.
Christian Louboutin: Innovating with Red Solesget joys
Christian Louboutin is celebrated for his innovative approach to footwear design, marked by his trademark red soles. This in-depth look at his life and career explores the origins of his creativity, the milestones in his journey, and the impact of his work on the fashion industry. Learn how Louboutin's bold vision and dedication to excellence have made his brand synonymous with luxury and style.
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdfkenid14983
Paul Haggis is undoubtedly a visionary filmmaker whose work has not only shaped cinema but has also pushed boundaries when it comes to diversity and representation within the industry. From his thought-provoking scripts to his engaging directorial style, Haggis has become a prominent figure in the world of film.
From Teacher to OnlyFans: Brianna Coppage's Story at 28get joys
At 28, Brianna Coppage left her teaching career to become an OnlyFans content creator. This bold move into digital entrepreneurship allowed her to harness her creativity and build a new identity. Brianna's experience highlights the intersection of technology and personal branding in today's economy.
The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...greendigital
Leonardo DiCaprio, a name synonymous with Hollywood stardom and acting excellence. has captivated audiences for decades with his talent and charisma. But, the Leonardo DiCaprio haircut is one aspect of his public persona that has garnered attention. From his early days as a teenage heartthrob to his current status as a seasoned actor and environmental activist. DiCaprio's hairstyles have evolved. reflecting both his personal growth and the changing trends in fashion. This article delves into the many phases of the Leonardo DiCaprio haircut. exploring its significance and impact on pop culture.
Leonardo DiCaprio House: A Journey Through His Extravagant Real Estate Portfoliogreendigital
Introduction
Leonardo DiCaprio, A name synonymous with Hollywood excellence. is not only known for his stellar acting career but also for his impressive real estate investments. The "Leonardo DiCaprio house" is a topic that piques the interest of many. as the Oscar-winning actor has amassed a diverse portfolio of luxurious properties. DiCaprio's homes reflect his varied tastes and commitment to sustainability. from retreats to historic mansions. This article will delve into the fascinating world of Leonardo DiCaprio's real estate. Exploring the details of his most notable residences. and the unique aspects that make them stand out.
Follow us on: Pinterest
Leonardo DiCaprio House: Malibu Beachfront Retreat
A Prime Location
His Malibu beachfront house is one of the most famous properties in Leonardo DiCaprio's real estate portfolio. Situated in the exclusive Carbon Beach. also known as "Billionaire's Beach," this property boasts stunning ocean views and private beach access. The "Leonardo DiCaprio house" in Malibu is a testament to the actor's love for the sea and his penchant for luxurious living.
Architectural Highlights
The Malibu house features a modern design with clean lines, large windows. and open spaces blending indoor and outdoor living. The expansive deck and patio areas provide ample space for entertaining guests or enjoying a quiet sunset. The house has state-of-the-art amenities. including a gourmet kitchen, a home theatre, and many guest suites.
Sustainable Features
Leonardo DiCaprio is a well-known environmental activist. whose Malibu house reflects his commitment to sustainability. The property incorporates solar panels, energy-efficient appliances, and sustainable building materials. The landscaping around the house is also designed to be water-efficient. featuring drought-resistant plants and intelligent irrigation systems.
Leonardo DiCaprio House: Hollywood Hills Hideaway
Privacy and Seclusion
Another remarkable property in Leonardo DiCaprio's collection is his Hollywood Hills house. This secluded retreat offers privacy and tranquility. making it an ideal escape from the hustle and bustle of Los Angeles. The "Leonardo DiCaprio house" in Hollywood Hills nestled among lush greenery. and offers panoramic views of the city and surrounding landscapes.
Design and Amenities
The Hollywood Hills house is a mid-century modern gem characterized by its sleek design and floor-to-ceiling windows. The open-concept living space is perfect for entertaining. while the cozy bedrooms provide a comfortable retreat. The property also features a swimming pool, and outdoor dining area. and a spacious deck that overlooks the cityscape.
Environmental Initiatives
The Hollywood Hills house incorporates several green features that are in line with DiCaprio's environmental values. The home has solar panels, energy-efficient lighting, and a rainwater harvesting system. Additionally, the landscaping designed to support local wildlife and promote
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Sagagreendigital
Introduction
The notion of Dwayne Johnson kidnapping seems straight out of a Hollywood thriller. Dwayne "The Rock" Johnson, known for his larger-than-life persona, immense popularity. and action-packed filmography, is the last person anyone would envision being a victim of kidnapping. Yet, the bizarre and riveting tale of such an incident, filled with twists and turns. has captured the imagination of many. In this article, we delve into the intricate details of this astonishing event. exploring every aspect, from the dramatic rescue operation to the aftermath and the lessons learned.
Follow us on: Pinterest
The Origins of the Dwayne Johnson Kidnapping Saga
Dwayne Johnson: A Brief Background
Before discussing the specifics of the kidnapping. it is crucial to understand who Dwayne Johnson is and why his kidnapping would be so significant. Born May 2, 1972, Dwayne Douglas Johnson is an American actor, producer, businessman. and former professional wrestler. Known by his ring name, "The Rock," he gained fame in the World Wrestling Federation (WWF, now WWE) before transitioning to a successful career in Hollywood.
Johnson's filmography includes blockbuster hits such as "The Fast and the Furious" series, "Jumanji," "Moana," and "San Andreas." His charismatic personality, impressive physique. and action-star status have made him a beloved figure worldwide. Thus, the news of his kidnapping would send shockwaves across the globe.
Setting the Scene: The Day of the Kidnapping
The incident of Dwayne Johnson's kidnapping began on an ordinary day. Johnson was filming his latest high-octane action film set to break box office records. The location was a remote yet scenic area. chosen for its rugged terrain and breathtaking vistas. perfect for the film's climactic scenes.
But, beneath the veneer of normalcy, a sinister plot was unfolding. Unbeknownst to Johnson and his team, a group of criminals had planned his abduction. hoping to leverage his celebrity status for a hefty ransom. The stage was set for an event that would soon dominate worldwide headlines and social media feeds.
The Abduction: Unfolding the Dwayne Johnson Kidnapping
The Moment of Capture
On the day of the kidnapping, everything seemed to be proceeding as usual on set. Johnson and his co-stars and crew were engrossed in shooting a particularly demanding scene. As the day wore on, the production team took a short break. providing the kidnappers with the perfect opportunity to strike.
The abduction was executed with military precision. A group of masked men, armed and organized, infiltrated the set. They created chaos, taking advantage of the confusion to isolate Johnson. Johnson was outnumbered and caught off guard despite his formidable strength and fighting skills. The kidnappers overpowered him, bundled him into a waiting vehicle. and sped away, leaving everyone on set in a state of shock and disbelief.
The Immediate Aftermath
The immediate aftermath of the Dwayne Johnson kidnappin
Modern Radio Frequency Access Control Systems: The Key to Efficiency and SafetyAITIX LLC
Today's fast-paced environment worries companies of all sizes about efficiency and security. Businesses are constantly looking for new and better solutions to solve their problems, whether it's data security or facility access. RFID for access control technologies have revolutionized this.
Top IPTV UK Providers of A Comprehensive Review.pdfXtreame HDTV
The television landscape in the UK has evolved significantly with the rise of Internet Protocol Television (IPTV). IPTV offers a modern alternative to traditional cable and satellite TV, allowing viewers to stream live TV, on-demand videos, and other multimedia content directly to their devices over the internet. This review provides an in-depth look at the top IPTV UK providers, their features, pricing, and what sets them apart.
Barbie Movie Review - The Astras.pdffffftheastras43
Barbie Movie Review has gotten brilliant surveys for its fun and creative story. Coordinated by Greta Gerwig, it stars Margot Robbie as Barbie and Ryan Gosling as Insight. Critics adore its perky humor, dynamic visuals, and intelligent take on the notorious doll's world. It's lauded for being engaging for both kids and grown-ups. The Astras profoundly prescribes observing the Barbie Review for a delightful and colorful cinematic involvement.https://theastras.com/hca-member-gradebooks/hca-gradebook-barbie/
Orpah Winfrey Dwayne Johnson: Titans of Influence and Inspirationgreendigital
Introduction
In the realm of entertainment, few names resonate as Orpah Winfrey Dwayne Johnson. Both figures have carved unique paths in the industry. achieving unparalleled success and becoming iconic symbols of perseverance, resilience, and inspiration. This article delves into the lives, careers. and enduring legacies of Orpah Winfrey Dwayne Johnson. exploring how their journeys intersect and what we can learn from their remarkable stories.
Follow us on: Pinterest
Early Life and Backgrounds
Orpah Winfrey: From Humble Beginnings to Media Mogul
Orpah Winfrey, often known as Oprah due to a misspelling on her birth certificate. was born on January 29, 1954, in Kosciusko, Mississippi. Raised in poverty by her grandmother, Winfrey's early life was marked by hardship and adversity. Despite these challenges. she demonstrated a keen intellect and an early talent for public speaking.
Winfrey's journey to success began with a scholarship to Tennessee State University. where she studied communication. Her first job in media was as a co-anchor for the local evening news in Nashville. This role paved the way for her eventual transition to talk show hosting. where she found her true calling.
Dwayne Johnson: From Wrestling Royalty to Hollywood Superstar
Dwayne Johnson, also known by his ring name "The Rock," was born on May 2, 1972, in Hayward, California. He comes from a family of professional wrestlers, with both his father, Rocky Johnson. and his grandfather, Peter Maivia, being notable figures in the wrestling world. Johnson's early life was spent moving between New Zealand and the United States. experiencing a variety of cultural influences.
Before entering the world of professional wrestling. Johnson had aspirations of becoming a professional football player. He played college football at the University of Miami. where he was part of a national championship team. But, injuries curtailed his football career, leading him to follow in his family's footsteps and enter the wrestling ring.
Career Milestones
Orpah Winfrey: The Queen of All Media
Winfrey's career breakthrough came in 1986 when she launched "The Oprah Winfrey Show." The show became a cultural phenomenon. drawing millions of viewers daily and earning many awards. Winfrey's empathetic and candid interviewing style resonated with audiences. helping her tackle diverse and often challenging topics.
Beyond her talk show, Winfrey expanded her empire to include the creation of Harpo Productions. a multimedia production company. She also launched "O, The Oprah Magazine" and OWN: Oprah Winfrey Network, further solidifying her status as a media mogul.
Dwayne Johnson: From The Ring to The Big Screen
Dwayne Johnson's wrestling career took off in the late 1990s. when he became one of the most charismatic and popular figures in WWE. His larger-than-life persona and catchphrases endeared him to fans. making him a household name. But, Johnson had ambitions beyond the wrestling ring.
In the early 20
Orpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
Csphtp1 15
1. Chapter 15 – Strings, Chars Outline 15.1 Introduction 15.2 Fundamentals of Characters and String s 15.3 String Constructors 15.4 String Indexer, Length Property and CopyTo Method 15.5 Comparing String s 15.6 String Method GetHashCode 15.7 Locating Characters and Substrings in String s 15.8 Extracting Substrings from String s 15.9 Concatenating String s 15.10 Miscellaneous String Methods 15.11 Class StringBuilder 15.12 StringBuilder Indexer, Length and Capacity Properties, and EnsureCapacity Method 15.13 StringBuilder Append and AppendFormat Methods 15.14 StringBuilder Insert , Remove and Replace Methods 15.15 Char Methods 15.16 Card Shuffling and Dealing Simulation 15.17 Regular Expressions and Class Regex
2.
3.
4.
5. StringConstructor.cs 1 // Fig. 15.1: StringConstructor.cs 2 // Demonstrating String class constructors. 3 4 using System; 5 using System.Windows.Forms; 6 7 // test several String class constructors 8 class StringConstructor 9 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string [] args ) 13 { 14 string output; 15 string originalString, string1, string2, 16 string3, string4; 17 18 char [] characterArray = 19 { 'b' , 'i' , 'r' , 't' , 'h' , ' ' , 'd' , 'a' , 'y' }; 20 21 // string initialization 22 originalString = "Welcome to C# programming!" ; 23 string1 = originalString; 24 string2 = new string ( characterArray ); 25 string3 = new string ( characterArray, 6 , 3 ); 26 string4 = new string ( 'C' , 5 ); 27 28 output = "string1 = " + "amp;quot;" + string1 + "amp;quot;" + 29 "string2 = " + "amp;quot;" + string2 + "amp;quot;" + 30 "string3 = " + "amp;quot;" + string3 + "amp;quot;" + 31 "string4 = " + "amp;quot;" + string4 + "amp;quot;" ; 32 String declarations Allocate char array characterArray to contain nine characters Assign literal string to string reference originalString Set string1 to reference the same string literal String2 assign to a new string String constructor takes a character array as argument String constructor takes a char array and two int arguments Starting index and count ArgumentOutOfRangeException thrown if element outside the bound Using string constructed with a character and an int specifying number of times to repeat character in the string Output the strings
6. StringConstructor.cs Program Output 33 MessageBox.Show( output, "String Class Constructors" , 34 MessageBoxButtons. OK , MessageBoxIcon. Information ); 35 36 } // end method Main 37 38 } // end class StringConstructor Shows the output
7.
8. StringMethods.cs 1 // Fig. 15.2: StringMethods.cs 2 // Using the indexer, property Length and method CopyTo 3 // of class String. 4 5 using System; 6 using System.Windows.Forms; 7 8 // creates string objects and displays results of using 9 // indexer and methods Length and CopyTo 10 class StringMethods 11 { 12 // The main entry point for the application. 13 [STAThread] 14 static void Main( string [] args ) 15 { 16 string string1, output; 17 char [] characterArray; 18 19 string1 = "hello there" ; 20 characterArray = new char [ 5 ]; 21 22 // output string 23 output = 24 "string1: amp;quot;" + string1 + "amp;quot;" ; 25 26 // test Length property 27 output += "Length of string1: " + string1.Length; 28 29 // loop through character in string1 and display 30 // reversed 31 output += "The string reversed is: " ; 32 33 for ( int i = string1.Length - 1 ; i >= 0 ; i-- ) 34 output += string1[ i ]; 35 String declarations String1 to store string literal “hello there” Append to output of string1 in reverse order
9. StringMethods.cs Program Output 36 // copy characters from string1 into characterArray 37 string1.CopyTo( 0 , characterArray, 0 , 5 ); 38 output += "The character array is: " ; 39 40 for ( int i = 0 ; i < characterArray.Length; i++ ) 41 output += characterArray[ i ]; 42 43 MessageBox.Show( output, "Demonstrating the string " + 44 "Indexer, Length Property and CopyTo method" , 45 MessageBoxButtons. OK , MessageBoxIcon. Information ); 46 47 } // end method Main 48 49 } // end class StringMethods Index to begin copying character array to copy to Index of location to put into character array Number of characters to copy from string Append the char array contents to string output Method Copyto called by string1
10.
11. StringCompare.cs 1 // Fig. 15.3: StringCompare.cs 2 // Comparing strings. 3 4 using System; 5 using System.Windows.Forms; 6 7 // compare a number of strings 8 class StringCompare 9 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string [] args ) 13 { 14 string string1 = "hello" ; 15 string string2 = "good bye" ; 16 string string3 = "Happy Birthday" ; 17 string string4 = "happy birthday" ; 18 string output; 19 20 // output values of four strings 21 output = "string1 = amp;quot;" + string1 + "amp;quot;" + 22 "string2 = amp;quot;" + string2 + "amp;quot;" + 23 "string3 = amp;quot;" + string3 + "amp;quot;" + 24 "string4 = amp;quot;" + string4 + "amp;quot;" ; 25 26 // test for equality using Equals method 27 if ( string1.Equals( "hello" ) ) 28 output += "string1 equals amp;quot;helloamp;quot;" ; 29 else 30 output += "string1 does not equal amp;quot;helloamp;quot;" ; 31 32 // test for equality with == 33 if ( string1 == "hello" ) 34 output += "string1 equals amp;quot;helloamp;quot;" ; Instance method Equals Compares the Unicode values in each string Equality operator
12. StringCompare.cs 35 else 36 output += "string1 does not equal amp;quot;helloamp;quot;" ; 37 38 // test for equality comparing case 39 if ( String .Equals( string3, string4 ) ) 40 output += "string3 equals string4" ; 41 else 42 output += "string3 does not equal string4" ; 43 44 // test CompareTo 45 output += "string1.CompareTo( string2 ) is " + 46 string1.CompareTo( string2 ) + "" + 47 "string2.CompareTo( string1 ) is " + 48 string2.CompareTo( string1 ) + "" + 49 "string1.CompareTo( string1 ) is " + 50 string1.CompareTo( string1 ) + "" + 51 "string3.CompareTo( string4 ) is " + 52 string3.CompareTo( string4 ) + "" + 53 "string4.CompareTo( string3 ) is " + 54 string4.CompareTo( string3 ) + "" ; 55 56 MessageBox.Show( output, "Demonstrating string " + 57 "comparisons" , MessageBoxButtons. OK , 58 MessageBoxIcon. Information ); 59 60 } // end method Main 61 62 } // end class StringCompare Test equality between string3 and string4 Output the appropriate message Static method Equals Method CompareTo called to compare string s
14. StringStartEnd.cs 1 // Fig. 15.4: StringStartEnd.cs 2 // Demonstrating StartsWith and EndsWith methods. 3 4 using System; 5 using System.Windows.Forms; 6 7 // testing StartsWith and EndsWith 8 class StringStartEnd 9 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string [] args ) 13 { 14 string [] strings = 15 { "started" , "starting" , "ended" , "ending" }; 16 string output = "" ; 17 18 //test every string to see if it starts with "st" 19 for ( int i = 0 ; i < strings.Length; i++ ) 20 21 if ( strings[ i ].StartsWith( "st" ) ) 22 output += "amp;quot;" + strings[ i ] + "amp;quot;" + 23 " starts with amp;quot;stamp;quot;" ; 24 25 output += "" ; 26 27 // test every string to see if it ends with "ed" 28 for ( int i = 0 ; i < strings.Length; i ++ ) 29 30 if ( strings[ i ].EndsWith( "ed" ) ) 31 output += "amp;quot;" + strings[ i ] + "amp;quot;" + 32 " ends with amp;quot;edamp;quot;" ; 33 Method StartsWith determines if a string instance starts with the string text passed to it Method EndsWith determines if a string instance ends with the string text passed to it Array of string s Contents define at time of declaration Method StartsWith takes a String argument If structure determine if string at index i starts with “st” Appends string[i] to string output Return true if test statement matched If structure determine if string at index i starts with “ed”
15. StringStartEnd.cs Program Output 34 MessageBox.Show( output, "Demonstrating StartsWith and " + 35 "EndsWith methods" , MessageBoxButtons. OK , 36 MessageBoxIcon. Information ); 37 38 } // end method Main 39 40 } // end class StringStartEnd
16.
17. StringHashCode.cs 1 // Fig. 15.5: StringHashCode.cs 2 // Demonstrating method GetHashCode of class String. 3 4 using System; 5 using System.Windows.Forms; 6 7 // testing the GetHashCode method 8 class StringHashCode 9 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string [] args ) 13 { 14 15 string string1 = "hello" ; 16 string string2 = "Hello" ; 17 string output; 18 19 output = "The hash code for amp;quot;" + string1 + 20 "amp;quot; is " + string1.GetHashCode() + "" ; 21 22 output += "The hash code for amp;quot;" + string2 + 23 "amp;quot; is " + string2.GetHashCode() + "" ; 24 25 MessageBox.Show( output, "Demonstrating String " + 26 "method GetHashCode" , MessageBoxButtons. OK , 27 MessageBoxIcon. Information ); 28 29 } // end method Main 30 31 } // end class StringHashCode Define two string s Method GetHashCode is called to calculate for string1 and string2
20. StringIndexMethods.cs 1 // Fig. 15.6: StringIndexMethods.cs 2 // Using String searching methods. 3 4 using System; 5 using System.Windows.Forms; 6 7 // testing indexing capabilities of strings 8 class StringIndexMethods 9 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string [] args ) 13 { 14 string letters = "abcdefghijklmabcdefghijklm" ; 15 string output = "" ; 16 char [] searchLetters = { 'c' , 'a' , '$' }; 17 18 // test IndexOf to locate a character in a string 19 output += "'c' is located at index " + 20 letters.IndexOf( 'c' ); 21 22 output += "'a' is located at index " + 23 letters.IndexOf( 'a' , 1 ); 24 25 output += "'$' is located at index " + 26 letters.IndexOf( '$' , 3 , 5 ); 27 28 // test LastIndexOf to find a character in a string 29 output += "Last 'c' is located at " + 30 "index " + letters.LastIndexOf( 'c' ); 31 32 output += "Last 'a' is located at index " + 33 letters.LastIndexOf( 'a' , 25 ); 34 Method IndexOf to locate first occurrence of substring in a string If successful IndexOf will return index of specified character or return -1 IndexOf takes two arguments, the character to search for and the initial index of the search IndexOf takes three arguments, the character to search for, the initial index of the search and the number of characters to search These outputs use the LastIndexOf method Takes the character as an argument to search Takes two argument, the character to search for and highest index to begin backward search
21. StringIndexMethods.cs 35 output += "Last '$' is located at index " + 36 letters.LastIndexOf( '$' , 15 , 5 ); 37 38 // test IndexOf to locate a substring in a string 39 output += "amp;quot;defamp;quot; is located at" + 40 " index " + letters.IndexOf( "def" ); 41 42 output += "amp;quot;defamp;quot; is located at index " + 43 letters.IndexOf( "def" , 7 ); 44 45 output += "amp;quot;helloamp;quot; is located at index " + 46 letters.IndexOf( "hello" , 5 , 15 ); 47 48 // test LastIndexOf to find a substring in a string 49 output += "Last amp;quot;defamp;quot; is located at index " + 50 letters.LastIndexOf( "def" ); 51 52 output += "Last amp;quot;defamp;quot; is located at " + 53 letters.LastIndexOf( "def" , 25 ); 54 55 output += "Last amp;quot;helloamp;quot; is located at index " + 56 letters.LastIndexOf( "hello" , 20 , 15 ); 57 58 // test IndexOfAny to find first occurrence of character 59 // in array 60 output += "First occurrence of 'c', 'a', '$' is " + 61 "located at " + letters.IndexOfAny( searchLetters ); 62 63 output += "First occurrence of 'c, 'a' or '$' is " + 64 "located at " + letters.IndexOfAny( searchLetters, 7 ); 65 66 output += "First occurrence of 'c', 'a' or '$' is " + 67 "located at " + letters.IndexOfAny( searchLetters, 20 , 5 ); 68 LastIndexOf search from the end of the string toward the beginning Argument takes the character to search for, the starting index to begin searching backward, and portion of string to search IndexOf and LastIndexOf perform similarly as LastIndexOf and IndexOf Instead of sending character arguments, these two methods search substring argument Method IndexOfAny take an array of characters as the first argument returns the index of first occurrence of any characters specified in the character array argument
22. StringIndexMethods.cs 69 // test LastIndexOfAny to find last occurrence of character 70 // in array 71 output += "Last occurrence of 'c', 'a' or '$' is " + 72 "located at " + letters.LastIndexOfAny( searchLetters ); 73 74 output += "Last occurrence of 'c', 'a' or '$' is " + 75 "located at " + letters.LastIndexOfAny( searchLetters, 1 ); 76 77 output += "Last occurrence of 'c', 'a' or '$' is " + 78 "located at " + letters.LastIndexOfAny( 79 searchLetters, 25 , 5 ); 80 81 MessageBox.Show( output, 82 "Demonstrating class index methods" , 83 MessageBoxButtons. OK , MessageBoxIcon. Information ); 84 85 } // end method Main 86 87 } // end class StringIndexMethods LastIndexOfAny takes an array of characters as the first argument Method LastIndexOfAny return the index of first occurrence of any of the character from the argument
25. SubString.cs 1 // Fig. 15.7: SubString.cs 2 // Demonstrating the String Substring method. 3 4 using System; 5 using System.Windows.Forms; 6 7 // creating substrings 8 class SubString 9 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string [] args ) 13 { 14 string letters = "abcdefghijklmabcdefghijklm" ; 15 string output = "" ; 16 17 // invoke Substring method and pass it one parameter 18 output += "Substring from index 20 to end is amp;quot;" + 19 letters.Substring( 20 ) + "amp;quot;" ; 20 21 // invoke Substring method and pass it two parameters 22 output += "Substring from index 0 to 6 is amp;quot;" + 23 letters.Substring( 0 , 6 ) + "amp;quot;" ; 24 25 MessageBox.Show( output, 26 "Demonstrating String method Substring" , 27 MessageBoxButtons. OK , MessageBoxIcon. Information ); 28 29 } // end method Main 30 31 } // end class SubString Substring methods takes one int argument Argument specifies the starting index to copy the character in the original string The returned substring contains a copy of the character from the specified index to the end If index specified is not inside the bound, then ArgumentOutOfRangeException thrown This example using Substring takes two int argument First argument specify the starting index Second argument specify length of the substring to be copied Substring return contains a copy of the specified characters from the original string
32. StringMiscellaneous2.cs 1 // Fig. 15.9: StringMiscellaneous2.cs 2 // Demonstrating String methods Replace, ToLower, ToUpper, Trim 3 // and ToString. 4 5 using System; 6 using System.Windows.Forms; 7 8 // creates strings using methods Replace, ToLower, ToUpper, Trim 9 class StringMethods2 10 { 11 // The main entry point for the application. 12 [STAThread] 13 static void Main( string [] args ) 14 { 15 string string1 = "cheers!" ; 16 string string2 = "GOOD BYE " ; 17 string string3 = " spaces " ; 18 string output; 19 20 output = "string1 = amp;quot;" + string1 + "amp;quot;" + 21 "string2 = amp;quot;" + string2 + "amp;quot;" + 22 "string3 = amp;quot;" + string3 + "amp;quot;" ; 23 24 // call method Replace 25 output += 26 "Replacing amp;quot;eamp;quot; with amp;quot;Eamp;quot; in string1: amp;quot;" + 27 string1.Replace( 'e' , 'E' ) + "amp;quot;" ; 28 29 // call ToLower and ToUpper 30 output += "string1.ToUpper() = amp;quot;" + 31 string1.ToUpper() + "amp;quot;string2.ToLower() = amp;quot;" + 32 string2.ToLower() + "amp;quot;" ; 33 Method Replace return new string with correct revision based on the argument Replace all instances of ‘e’ with ‘E’ in string1 String to search for String to replace with Original string return if no match occur Method ToLower return a new string from string2 by lowercase equivalence
33. StringMiscellaneous2.cs Program Output 34 // call Trim method 35 output += "string3 after trim = amp;quot;" + 36 string3.Trim() + "amp;quot;" ; 37 38 // call ToString method 39 output += "string1 = amp;quot;" + string1.ToString() + "amp;quot;" ; 40 41 MessageBox.Show( output, 42 "Demonstrating various string methods" , 43 MessageBoxButtons. OK , MessageBoxIcon. Information ); 44 45 } // end method Main 46 47 } // end class StringMethods2 Method Trim to remove all whitespace character at the beginning or end of string3 Return new string omitting leading or trailing whitespace character Method ToString to show string1 have not been modified
34.
35. StringBuilderConstructor.cs 1 // Fig. 15.10: StringBuilderConstructor.cs 2 // Demonstrating StringBuilder class constructors. 3 4 using System; 5 using System.Windows.Forms; 6 using System.Text; 7 8 // creates three StringBuilder with three constructors 9 class StringBuilderConstructor 10 { 11 // The main entry point for the application. 12 [STAThread] 13 static void Main( string [] args ) 14 { 15 StringBuilder buffer1, buffer2, buffer3; 16 string output; 17 18 buffer1 = new StringBuilder(); 19 buffer2 = new StringBuilder( 10 ); 20 buffer3 = new StringBuilder( "hello" ); 21 22 output = "buffer1 = amp;quot;" + buffer1.ToString() + "amp;quot;" ; 23 24 output += "buffer2 = amp;quot;" + buffer2.ToString() + "amp;quot;" ; 25 26 output += "buffer3 = amp;quot;" + buffer3.ToString() + "amp;quot;" ; 27 28 MessageBox.Show( output, 29 "Demonstrating StringBuilder class constructors" , 30 MessageBoxButtons. OK , MessageBoxIcon. Information ); 31 32 } // end method Main 33 34 } // end class StringBuilderConstructor No-argument StringBuilder constructor with default initial capacity at 16 Stringbuilder with no characters and initial size at 10 Stringbuilder with string argument Initial capacity is the smallest power of two greater than the number of characters in the string argument Method ToString to obtain string representation of the StringBuilders’ content Method returns the StringBuilders’ underlying string
38. StringBuilderFeatures.cs 1 // Fig. 15.11: StringBuilderFeatures.cs 2 // Demonstrating some features of class StringBuilder. 3 4 using System; 5 using System.Windows.Forms; 6 using System.Text; 7 8 // uses some of class StringBuilder’s methods 9 class StringBuilderFeatures 10 { 11 // The main entry point for the application. 12 [STAThread] 13 static void Main( string [] args ) 14 { 15 StringBuilder buffer = 16 new StringBuilder( "Hello, how are you?" ); 17 18 // use Length and Capacity properties 19 string output = "buffer = " + buffer.ToString() + 20 "Length = " + buffer.Length + 21 "Capacity = " + buffer.Capacity; 22 23 // use EnsureCapacity method 24 buffer.EnsureCapacity( 75 ); 25 26 output += "New capacity = " + 27 buffer.Capacity; 28 29 // truncate StringBuilder by setting Length property 30 buffer.Length = 10 ; 31 32 output += "New length = " + 33 buffer.Length + "buffer = " ; 34 Declare a StringBuilder name buffer Take string argument to initialize its value to the actual string Append to output the content of StringBuilder Append to output the length of StringBuilder Append to output the capacity of StringBuilder Expands the capacity to a minimum of 75 characters Uses Length ’s Set accessor to set length of the Stringbuilder to 10 Could discard any character that doesn’t fit into specified length Would append null characters to the end of the StringBuilder if Length exceed space needed
39. StringBuilderFeatures.cs Program Output 35 // use StringBuilder indexer 36 for ( int i = 0 ; i < buffer.Length; i++ ) 37 output += buffer[ i ]; 38 39 MessageBox.Show( output, "StringBuilder features" , 40 MessageBoxButtons. OK , MessageBoxIcon. Information ); 41 42 } // end method Main 43 44 } // end class StringBuilderFeatures New length allow for the StringBuilder to be of only 10, truncate any preceding characters
40.
41. StringBuilderAppend.cs 1 // Fig. 15.12: StringBuilderAppend.cs 2 // Demonstrating StringBuilder Append methods. 3 4 using System; 5 using System.Windows.Forms; 6 using System.Text; 7 8 // testing the Append method 9 class StringBuilderAppend 10 { 11 // The main entry point for the application. 12 [STAThread] 13 static void Main( string [] args ) 14 { 15 object objectValue = "hello" ; 16 string stringValue = "good bye" ; 17 char [] characterArray = { 'a' , 'b' , 'c' , 'd' , 18 'e' , 'f' }; 19 20 bool booleanValue = true ; 21 char characterValue = 'Z' ; 22 int integerValue = 7 ; 23 long longValue = 1000000 ; 24 float floatValue = 2.5F ; 25 double doubleValue = 33.333 ; 26 StringBuilder buffer = new StringBuilder(); 27 28 // use method Append to append values to buffer 29 buffer.Append( objectValue ); 30 buffer.Append( " " ); 31 buffer.Append( stringValue ); 32 buffer.Append( " " ); 33 buffer.Append( characterArray ); 34 buffer.Append( " " ); Examples of overloaded Append methods Various different type of objects created to append StringBuilder buffer created for this example
42. StringBuilderAppend.cs Program Output 35 buffer.Append( characterArray, 0 , 3 ); 36 buffer.Append( " " ); 37 buffer.Append( booleanValue ); 38 buffer.Append( " " ); 39 buffer.Append( characterValue ); 40 buffer.Append( " " ); 41 buffer.Append( integerValue ); 42 buffer.Append( " " ); 43 buffer.Append( longValue ); 44 buffer.Append( " " ); 45 buffer.Append( floatValue ); 46 buffer.Append( " " ); 47 buffer.Append( doubleValue ); 48 49 MessageBox.Show( "buffer = " + buffer.ToString(), 50 "Demonstrating StringBuilder append method" , 51 MessageBoxButtons. OK , MessageBoxIcon. Information ); 52 53 } // end method Main 54 55 } // end class StringBuilderAppend More overloaded Append method to attach object onto buffer Append behave similarly to the + operator, used with string s Appends all of the objects created from lines 15-26
43. StringBuilderAppendFormat.cs 1 // Fig. 15.13: StringBuilderAppendFormat.cs 2 // Demonstrating method AppendFormat. 3 4 using System; 5 using System.Windows.Forms; 6 using System.Text; 7 8 // use the AppendFormat method 9 class StringBuilderAppendFormat 10 { 11 // The main entry point for the application. 12 [STAThread] 13 static void Main( string [] args ) 14 { 15 StringBuilder buffer = new StringBuilder(); 16 string string1, string2; 17 18 // formatted string 19 string1 = "This {0} costs: {1:C}." ; 20 21 // string1 argument array 22 object [] objectArray = new object [ 2 ]; 23 24 objectArray[ 0 ] = "car" ; 25 objectArray[ 1 ] = 1234.56 ; 26 27 // append to buffer formatted string with argument 28 buffer.AppendFormat( string1, objectArray ); 29 30 // formatted string 31 string2 = "Number:{0:d3}." + 32 "Number right aligned with spaces:{0, 4}." + 33 "Number left aligned with spaces:{0, -4}." ; 34 Create string1 with formatting information Number of argument to format Format as currency value AppendFormat takes two parameters String1 to specify the format objectArray serve as the arguments to the format string Argument referred by “{0}” is the object array at index 0 Another string used for formatting Specify that first argument will be formatted as a three-digit decimal Specify that argument should have four characters and be right aligned Specify that the string should be left aligned
44. StringBuilderAppendFormat.cs Program Output 35 // append to buffer formatted string with argument 36 buffer.AppendFormat( string2, 5 ); 37 38 // display formatted strings 39 MessageBox.Show( buffer.ToString(), "Using AppendFormat" , 40 MessageBoxButtons. OK , MessageBoxIcon. Information ); 41 42 } // end method Main 43 44 } // end class StringBuilderAppendFormat Version of AppendFormat that takes two parameters String containing a format An object to which the format is applied Output shows the result of applying AppendFormat with the respective arguments
45.
46. StringBuilderInsertRemove.cs 1 // Fig. 15.14: StringBuilderInsertRemove.cs 2 // Demonstrating methods Insert and Remove of the 3 // StringBuilder class. 4 5 using System; 6 using System.Windows.Forms; 7 using System.Text; 8 9 // test the Insert and Remove methods 10 class StringBuilderInsertRemove 11 { 12 // The main entry point for the application. 13 [STAThread] 14 static void Main( string [] args ) 15 { 16 object objectValue = "hello" ; 17 string stringValue = "good bye" ; 18 char [] characterArray = { 'a' , 'b' , 'c' , 19 'd' , 'e' , 'f' }; 20 21 bool booleanValue = true ; 22 char characterValue = 'K' ; 23 int integerValue = 7 ; 24 long longValue = 10000000 ; 25 float floatValue = 2.5F ; 26 double doubleValue = 33.333 ; 27 StringBuilder buffer = new StringBuilder(); 28 string output; 29 30 // insert values into buffer 31 buffer.Insert( 0 , objectValue); 32 buffer.Insert( 0 , " " ); 33 buffer.Insert( 0 , stringValue); 34 buffer.Insert( 0 , " " ); Various different type of objects created to append Uses the Insert method
47. StringBuilderInsertRemove.cs 35 buffer.Insert( 0 , characterArray); 36 buffer.Insert( 0 , " " ); 37 buffer.Insert( 0 , booleanValue); 38 buffer.Insert( 0 , " " ); 39 buffer.Insert( 0 , characterValue); 40 buffer.Insert( 0 , " " ); 41 buffer.Insert( 0 , integerValue); 42 buffer.Insert( 0 , " " ); 43 buffer.Insert( 0 , longValue); 44 buffer.Insert( 0 , " " ); 45 buffer.Insert( 0 , floatValue); 46 buffer.Insert( 0 , " " ); 47 buffer.Insert( 0 , doubleValue); 48 buffer.Insert( 0 , " " ); 49 50 output = "buffer after inserts: " + 51 buffer.ToString() + "" ; 52 53 buffer.Remove( 10 , 1 ); // delete 2 in 2.5 54 buffer.Remove( 2 , 4 ); // delete .333 in 33.333 55 56 output += "buffer after Removes:" + 57 buffer.ToString(); 58 59 MessageBox.Show( output, "Demonstrating StringBuilder " + 60 "Insert and Remove methods" , MessageBoxButtons. OK , 61 MessageBoxIcon. Information ); 62 63 } // end method Main 64 65 } // end class StringBuilderInsertRemove Output buffer with all of the various object inserted Output display in reverse order from which it was inserted Stream through the buffer to reach appropriate location of the string Specify the extent of the removal Output the new string from as the result from method Remove
49. StringBuilderReplace.cs 1 // Fig. 15.15: StringBuilderReplace.cs 2 // Demonstrating method Replace. 3 4 using System; 5 using System.Windows.Forms; 6 using System.Text; 7 8 // testing the Replace method 9 class StringBuilderReplace 10 { 11 // The main entry point for the application. 12 [STAThread] 13 static void Main( string [] args ) 14 { 15 StringBuilder builder1 = 16 new StringBuilder( "Happy Birthday Jane" ); 17 18 StringBuilder builder2 = 19 new StringBuilder( "good bye greg" ); 20 21 string output = "Before replacements:" + 22 builder1.ToString() + "" + builder2.ToString(); 23 24 builder1.Replace( "Jane" , "Greg" ); 25 builder2.Replace( 'g' , 'G' , 0 , 5 ); 26 27 output += "After replacements:" + 28 builder1.ToString() + "" + builder2.ToString(); 29 StringBuilder created with specified string s Method Replace called Replace “Jane” with “Greg” Replaces all instances of the first character with the second Index specify begin point and continuation span
50. StringBuilderReplace.cs Program Output 30 MessageBox.Show( output, 31 "Using StringBuilder method Replace" , 32 MessageBoxButtons. OK , MessageBoxIcon. Information ); 33 34 } // end method Main 35 36 } // end class StringBuilderReplace Result from replacing “Jane” with “Greg” The continuation span of five was insufficient for “greg” to be altered
51.
52. CharMethods.cs 1 // Fig. 15.16: CharMethods.cs 2 // Demonstrates static character testing methods 3 // from Char structure 4 5 using System; 6 using System.Drawing; 7 using System.Collections; 8 using System.ComponentModel; 9 using System.Windows.Forms; 10 using System.Data; 11 12 // Form displays information about specific characters. 13 public class StaticCharMethods : System.Windows.Forms.Form 14 { 15 private System.Windows.Forms.Label enterLabel; 16 private System.Windows.Forms.TextBox inputTextBox; 17 private System.Windows.Forms.Button analyzeButton; 18 private System.Windows.Forms.TextBox outputTextBox; 19 20 private System.ComponentModel.Container components = null ; 21 22 // The main entry point for the application. 23 [STAThread] 24 static void Main() 25 { 26 Application.Run( new StaticCharMethods() ); 27 } 28 29 // Visual Studio .NET generated code 30 TextBox for user to input characters TextBox to displays the output of analysis
53. CharMethods.cs 31 // handle analyzeButton_Click 32 private void analyzeButton_Click( 33 object sender, System.EventArgs e ) 34 { 35 char character = Convert.ToChar( inputTextBox.Text ); 36 BuildOutput( character ); 37 } 38 39 // display character information in outputTextBox 40 private void BuildOutput( char inputCharacter ) 41 { 42 string output; 43 44 output = "is digit: " + 45 Char.IsDigit( inputCharacter ) + "" ; 46 47 output += "is letter: " + 48 Char.IsLetter( inputCharacter ) + "" ; 49 50 output += "is letter or digit: " + 51 Char.IsLetterOrDigit( inputCharacter ) + "" ; 52 53 output += "is lower case: " + 54 Char.IsLower( inputCharacter ) + "" ; 55 56 output += "is upper case: " + 57 Char.IsUpper( inputCharacter ) + "" ; 58 59 output += "to upper case: " + 60 Char.ToUpper( inputCharacter ) + "" ; 61 62 output += "to lower case: " + 63 Char.ToLower( inputCharacter ) + "" ; 64 Event handler invoke when user click Analyze Character Convert entered data from a string to a Char Method Convert.ToChar Method BuildOutput Char method IsDigit , return true if inputCharacter is define as a digit Char method IsLetter return true if inputCharacter is a letter Char method IsLetterOrDigit return true if inputCharacter is a letter or digit Char method IsLower return true if inputCharacter is a lowercase letter Char method IsUpper return true if inputCharacter is an uppercase letter Char method ToUpper convert inputCharacter to uppercase equivalent Char method ToLower convert inputCharacter to lowercase equivalent Method will return original argument if no conversion made
54. CharMethods.cs Program Output 65 output += "is punctuation: " + 66 Char.IsPunctuation( inputCharacter ) + "" ; 67 68 output += "is symbol: " + Char.IsSymbol( inputCharacter ); 69 70 outputTextBox.Text = output; 71 72 } // end method BuildOutput 73 74 } // end class StaticCharMethods Char method IsPunctuation return true if inputCharacter is a punctuation mark Char method IsSymbol return true if inputCharacter is a symbol
55.
56. Card.cs 1 // Fig. 15.17: Card.cs 2 // Stores suit and face information on each card. 3 4 using System; 5 6 // the representation of a card 7 public class Card 8 { 9 private string face; 10 private string suit; 11 12 public Card( string faceValue, 13 string suitValue ) 14 { 15 face = faceValue; 16 suit = suitValue; 17 18 } // end constructor 19 20 public override string ToString() 21 { 22 return face + " of " + suit; 23 24 } // end method ToString 25 26 } // end class Card String instance variables, face and suit Constructor receives two string s that it use to initialize face and suit Method creates a string consisting of the face and suit of the card
57. DeckOfCards.cs 1 // Fig. 15.18: DeckOfCards.cs 2 // Simulating card drawing and shuffling. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 // provides the functionality for the form 12 public class DeckForm : System.Windows.Forms.Form 13 { 14 private System.Windows.Forms.Button dealButton; 15 private System.Windows.Forms.Button shuffleButton; 16 17 private System.Windows.Forms.Label displayLabel; 18 private System.Windows.Forms.Label statusLabel; 19 20 private System.ComponentModel.Container components = null ; 21 22 private Card[] deck = new Card[ 52 ]; 23 private int currentCard; 24 25 // main entry point for application 26 [STAThread] 27 static void Main() 28 { 29 Application.Run( new deckForm() ); 30 } 31 32 // Visual Studio .NET generated code 33 Application Deckform to create a deck of 52 playing cards using Card objects User to have Shuffle Cards as an option User can Deal Card by pressing its button Each card dealt is displayed
58. DeckOfCards.cs 34 // handles form at load time 35 private void DeckForm_Load( 36 object sender, System.EventArgs e ) 37 { 38 string [] faces = { "Ace" , "Deuce" , "Three" , "Four" , 39 "Five" , "Six" , "Seven" , "Eight" , 40 "Nine" , "Ten" , "Jack" , "Queen" , 41 "King" }; 42 43 string [] suits = { "Hearts" , "Diamonds" , "Clubs" , 44 "Spades" }; 45 46 // no cards have been drawn 47 currentCard = -1 ; 48 49 // initialize deck 50 for ( int i = 0 ; i < deck.Length; i++ ) 51 deck[ i ] = new Card( faces[ i % 13 ], suits[ i % 4 ] ); 52 53 } // end method deckForm_Load 54 55 // handles dealButton Click 56 private void dealButton_Click( 57 object sender, System.EventArgs e ) 58 { 59 Card dealt = DealCard(); 60 61 // if dealt card is null, then no cards left 62 // player must shuffle cards 63 if ( dealt != null ) 64 { 65 displayLabel.Text = dealt.ToString(); 66 statusLabel.Text = "Card #: " + currentCard; 67 } For structure used to fill the deck array with Card s Modulus calculation ensure that value fall in a specific range Event handler dealButton_Click invokes method DealCard to get next card in the array If deck is not empty, method returns a Card object reference, otherwise it returns null Display card in displayLabel Card number display in the statusLabel Enumeration for possible face types Enumeration for all possible suits
59. DeckOfCards.cs 68 else 69 { 70 displayLabel.Text = "NO MORE CARDS TO DEAL" ; 71 statusLabel.Text = "Shuffle cards to continue" ; 72 } 73 } 74 75 // shuffle cards 76 private void Shuffle() 77 { 78 Random randomNumber = new Random(); 79 Card temporaryValue; 80 81 currentCard = -1 ; 82 83 // swap each card with random card 84 for ( int i = 0 ; i < deck.Length; i++ ) 85 { 86 int j = randomNumber.Next( 52 ); 87 88 // swap cards 89 temporaryValue = deck[ i ]; 90 deck[ i ] = deck[ j ]; 91 deck[ j ] = temporaryValue; 92 } 93 94 dealButton.Enabled = true ; 95 96 } // end method Shuffle 97 String “NO MORE CARDS TO DEAL ” is displayed in displayLabel if DealCard is null String “Shuffle cards to continue ” is displayed in statusLabel if DealCard is null The for loops go through all 52 cards (0-51), randomly picks numbers between 0 and 51 Current Card object and randomly selected Card are swapped in the array Method Shuffle makes a total of 52 swaps during single pass of the entire array
60. DeckOfCards.cs 98 private Card DealCard() 99 { 100 // if there is a card to deal then deal it 101 // otherwise signal that cards need to be shuffled by 102 // disabling dealButton and returning null 103 if ( currentCard + 1 < deck.Length ) 104 { 105 currentCard++; 106 return deck[ currentCard ]; 107 } 108 else 109 { 110 dealButton.Enabled = false ; 111 return null ; 112 } 113 114 } // end method DealCard 115 116 // handles shuffleButton Click 117 private void shuffleButton_Click( 118 object sender, System.EventArgs e ) 119 { 120 displayLabel.Text = "SHUFFLING..." ; 121 Shuffle(); 122 displayLabel.Text = "DECK IS SHUFFLED" ; 123 124 } // end method shuffleButton_Click 125 126 } // end class deckForm Method shuffleButton_Click invokes method Shuffle to shuffle the cards When the call to Shuffle returns, displayLabel displays “ DECK IS SHUFFLED ”
65. RegexMatches.cs 1 // Fig. 15.20: RegexMatches.cs 2 // Demonstrating Class Regex. 3 4 using System; 5 using System.Windows.Forms; 6 using System.Text.RegularExpressions; 7 8 // test out regular expressions 9 class RegexMatches 10 { 11 // The main entry point for the application. 12 [STAThread] 13 static void Main( string [] args ) 14 { 15 string output = "" ; 16 17 // create regular expression 18 Regex expression = 19 new Regex( @ "J.*[0-35-9]--" ); 20 21 string string1 = "Jane's Birthday is 05-12-75" + 22 "Dave's Birthday is 11-04-68" + 23 "John's Birthday is 04-28-73" + 24 "Joe's Birthday is 12-17-77" ; 25 26 // match regular expression to string and 27 // print out all matches 28 foreach ( Match myMatch in expression.Matches( string1 ) ) 29 output += myMatch.ToString() + "" ; 30 Create instance of class Regex Regular expression Match only digits in the range 0 – 3 and 5 - 9 Represent a two digit number foreach loop iterates through each Match “ .*” matches any number of unspecified characters The dot character matches any single character except a newline character Character “J” is a literal character “ ” will match any numeric digit
66. RegexMatches.cs Program Output 31 MessageBox.Show( output, "Using class Regex" , 32 MessageBoxButtons. OK , MessageBoxIcon. Information ); 33 34 } // end method Main 35 36 } // end class RegexMatches Output show the two matches from string1 that have same pattern specified
68. Validate.cs 1 // Fig. 15.22: Validate.cs 2 // Validate user information using regular expressions. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 using System.Text.RegularExpressions; 11 12 // use regular expressions to validate strings 13 public class ValidateForm : System.Windows.Forms.Form 14 { 15 private System.Windows.Forms.Label phoneLabel; 16 private System.Windows.Forms.Label zipLabel; 17 private System.Windows.Forms.Label stateLabel; 18 private System.Windows.Forms.Label cityLabel; 19 private System.Windows.Forms.Label addressLabel; 20 private System.Windows.Forms.Label firstLabel; 21 private System.Windows.Forms.Label lastLabel; 22 23 private System.Windows.Forms.Button okButton; 24 25 private System.Windows.Forms.TextBox phoneTextBox; 26 private System.Windows.Forms.TextBox zipTextBox; 27 private System.Windows.Forms.TextBox stateTextBox; 28 private System.Windows.Forms.TextBox cityTextBox; 29 private System.Windows.Forms.TextBox addressTextBox; 30 private System.Windows.Forms.TextBox firstTextBox; 31 private System.Windows.Forms.TextBox lastTextBox; 32 33 private System.ComponentModel.Container components = null ; 34
69. Validate.cs 35 // The main entry point for the application. 36 [STAThread] 37 static void Main() 38 { 39 Application.Run( new validateForm() ); 40 } 41 42 // Visual Studio .NET generated code 43 44 // handles okButton Click event 45 private void okButton_Click( 46 object sender, System.EventArgs e ) 47 { 48 // ensures no textboxes are empty 49 if ( lastTextBox.Text == "" || firstTextBox.Text == "" || 50 addressTextBox.Text == "" || cityTextBox.Text == "" || 51 stateTextBox.Text == "" || zipTextBox.Text == "" || 52 phoneTextBox.Text == "" ) 53 { 54 // display popup box 55 MessageBox.Show( "Please fill in all fields" , "Error" , 56 MessageBoxButtons. OK , MessageBoxIcon. Error ); 57 58 // set focus to lastTextBox 59 lastTextBox.Focus(); 60 61 return ; 62 } 63 Method okButton_Click to ensure that all data fields were filled in Will inform if a certain field was left blank Instance method Focus of class TextBox Method Focus places the cursor within the TextBox that made the call Program control then exits the event handler
70. Validate.cs 64 // if last name format invalid show message 65 if ( !Regex.Match( lastTextBox.Text, 66 @ "^[A-Z][a-zA-Z]*$" ).Success ) 67 { 68 // last name was incorrect 69 MessageBox.Show( "Invalid Last Name" , "Message" , 70 MessageBoxButtons. OK , MessageBoxIcon. Error ); 71 lastTextBox.Focus(); 72 73 return ; 74 } 75 76 // if first name format invalid show message 77 if ( !Regex.Match( firstTextBox.Text, 78 @ "^[A-Z][a-zA-Z]*$" ).Success ) 79 { 80 // first name was incorrect 81 MessageBox.Show( "Invalid First Name" , "Message" , 82 MessageBoxButtons. OK , MessageBoxIcon. Error ); 83 firstTextBox.Focus(); 84 85 return ; 86 } 87 88 // if address format invalid show message 89 if ( !Regex.Match( addressTextBox.Text, 90 @ "^[0-9]++([a-zA-Z]+|[a-zA-Z]+[a-zA-Z]+)$" ).Success ) 91 { 92 // address was incorrect 93 MessageBox.Show( "Invalid Address" , "Message" , 94 MessageBoxButtons. OK , MessageBoxIcon. Error ); 95 addressTextBox.Focus(); 96 97 return ; 98 } Last Name is validated first If the Success property of Match instance is true Control then moves on to validate First Name Same process will occur for the remaining TextBox es “ *” quantifier signifies that the second range of characters may occur zero or more times “ ” matches a single whitespace character Last Name and First Name fields both accept strings of any length that begin with uppercase letter Address field accepts anything in the format of: “10 Broadway” or “10 Main Street”
71. Validate.cs 99 100 // if city format invalid show message 101 if ( !Regex.Match( cityTextBox.Text, 102 @ "^([a-zA-Z]+|[a-zA-Z]+[a-zA-Z]+)$" ).Success ) 103 { 104 // city was incorrect 105 MessageBox.Show( "Invalid City" , "Message" , 106 MessageBoxButtons. OK , MessageBoxIcon. Error ); 107 cityTextBox.Focus(); 108 109 return ; 110 } 111 112 // if state format invalid show message 113 if ( !Regex.Match( stateTextBox.Text, 114 @ "^([a-zA-Z]+|[a-zA-Z]+[a-zA-Z]+)$" ).Success ) 115 { 116 // state was incorrect 117 MessageBox.Show( "Invalid State" , "Message" , 118 MessageBoxButtons. OK , MessageBoxIcon. Error ); 119 stateTextBox.Focus(); 120 121 return ; 122 } 123 124 // if zip code format invalid show message 125 if ( !Regex.Match( zipTextBox.Text, @ "^{5}$" ).Success ) 126 { 127 // zip was incorrect 128 MessageBox.Show( "Invalid Zip Code" , "Message" , 129 MessageBoxButtons. OK , MessageBoxIcon. Error ); 130 zipTextBox.Focus(); 131 132 return ; 133 } More check to validate the rest of the TextBox es “ {5}” matches any five digits City and State match any word of at least one character or any two words of at least one character if the words are separated by a single space Must be 5 digits, exactly
72. Validate.cs 134 135 // if phone number format invalid show message 136 if ( !Regex.Match( phoneTextBox.Text, 137 @ "^[1-9]{2}-[1-9]{2}-{4}$" ).Success ) 138 { 139 // phone number was incorrect 140 MessageBox.Show( "Invalid Phone Number" , "Message" , 141 MessageBoxButtons. OK , MessageBoxIcon. Error ); 142 phoneTextBox.Focus(); 143 144 return ; 145 } 146 147 // information is valid, signal user and exit application 148 this .Hide(); 149 MessageBox.Show( "Thank You!" , "Information Correct" , 150 MessageBoxButtons. OK , MessageBoxIcon. Information ); 151 152 Application.Exit(); 153 154 } // end method okButton_Click 155 156 } // end class ValidateForm If Success is signaled throughout the validation the program signals it then quits The “^” and “$” expression forces regular expression to evaluate entire string Phone must be the form xxx-yyy-yyy
76. RegexSubstitution.cs 1 // Fig. 15.23: RegexSubstitution.cs 2 // Using Regex method Replace. 3 4 using System; 5 using System.Text.RegularExpressions; 6 using System.Windows.Forms; 7 8 // Summary description for RegexSubstitution. 9 public class RegexSubstitution1 10 { 11 12 // The main entry point for the application. 13 static void Main( string[] args ) 14 { 15 string testString1 = 16 "This sentence ends in 5 stars *****" ; 17 18 string testString2 = "1, 2, 3, 4, 5, 6, 7, 8" ; 19 Regex testRegex1 = new Regex( "stars" ); 20 Regex testRegex2 = new Regex( @ "" ); 21 string [] results; 22 string output = "Original String 1" + testString1; 23 24 testString1 = Regex.Replace( testString1, @ "" , "^" ); 25 26 output += "^ substituted for *" + testString1; 27 28 testString1 = testRegex1.Replace( testString1, "carets" ); 29 30 output += "amp;quot;caretsamp;quot; substituted for amp;quot;starsamp;quot;" + 31 testString1; 32 33 output += "Every word replaced by amp;quot;wordamp;quot;" + 34 Regex.Replace( testString1, @ "+" , "word" ); 35 Static version of Replace The string to modify The string containing regular expression to match The replacement string Replace every instance of “*” in testString1 with “^” Instance method Replace uses regular expression passed to constructor Regular expression “ stars ” in testString1 is replaced with “ carets ” Instantiates testRegex2 with argument @””
77. RegexSubstitution.cs 36 output += "Original String 2" + testString2; 37 38 output += "First 3 digits replaced by amp;quot;digitamp;quot;" + 39 testRegex2.Replace( testString2, "digit" , 3 ); 40 41 output += "String split at commas[" ; 42 43 results = Regex.Split( testString2, @ ",*" ); 44 45 foreach ( string resultString in results ) 46 { 47 output += "amp;quot;" + resultString + "amp;quot;, " ; 48 } 49 50 output = output.Substring( 0 , output.Length - 2 ) + "]" ; 51 52 MessageBox.Show( output, 53 "Substitution using regular expressions" ); 54 55 } // end method Main 56 57 } // end class RegexSubstitution Instance method Replace takes three argument A string to modify A string containing the replacement text An int specifying the number of replacements to make Replaces first three instances of a digit in testString2 with “ digit ” Method split divides a string into several substrings Original string is broken in any location that matches specified regular expression Method Split returns array of substrings between matches for the regular expression Using static version of method Split String to split The regular expression