Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Similar documents
Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

String sequence of characters string Unicode Characters immutable they cannot be changed after they have been created.

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

Lab 14 & 15: String Handling

SWE344. Internet Protocols and Client-Server Programming

File Handling Programming 1 C# Programming. Rob Miles

2. All the strings gets collected in a special memory are for Strings called " String constant pool".

More non-primitive types Lesson 06

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Creating Strings. String Length

Building Strings and Exploring String Class:

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Lecture Notes K.Yellaswamy Assistant Professor K L University

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

"Hello" " This " + "is String " + "concatenation"

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Follow this and additional works at: Part of the Programming Languages and Compilers Commons

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

Chapter 14: Files and Streams

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Pace University. Fundamental Concepts of CS121 1

CHAPTER 6 MOST COMMONLY USED LIBRARIES

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

C# Data Manipulation

Introduction to C# Applications

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

appreciate the difference between a char and a string understand and use the String class methods

C# Data Manipulation

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CSE 143 Au03 Midterm 2 Page 1 of 7

String. Other languages that implement strings as character arrays

Object-Oriented Programming

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Java Identifiers, Data Types & Variables

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

IST311 Chapter13.NET Files (Part2)

OOP-Lecture Java Loop Controls: 1 Lecturer: Hawraa Sh. You can use one of the following three loops: while Loop do...while Loop for Loop

CSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7. Question 1. (2 points) What is the difference between a stream and a file?

Preview from Notesale.co.uk Page 9 of 108

F# - BASIC I/O. Core.Printf Module. Format Specifications. Basic Input Output includes

VARIABLES, DATA TYPES,

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

This tutorial has been prepared for the beginners to help them understand basics of c# Programming.

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

Question 1. (2 points) What is the difference between a stream and a file?

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

STUDENT LESSON A10 The String Class

A variable is a name for a location in memory A variable must be declared

Introduction to Programming Using Java (98-388)

Intel Integrated Performance Primitives for Intel Architecture

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Objectives. Introduce static keyword examine syntax describe common uses

Chapter 10 Characters, Strings, and the string class

Java Programming. String Processing. 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved.

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination

.Net Technologies. Components of.net Framework

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Getting started with Java

Chapter 10: Text Processing and More about Wrapper Classes

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

CSCE 110 PROGRAMMING FUNDAMENTALS

Software and Programming 1

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Strings, Strings and characters, String class methods. JAVA Standard Edition

Fundamentals of Programming Session 23

York University Fall 2001 / Test #1 Department of Computer Science

Visual C# Instructor s Manual Table of Contents

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

We now start exploring some key elements of the Java programming language and ways of performing I/O

05/31/2009. Data Files

Full file at

Language Reference Manual

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Outline. Java Compiler and Virtual Machine. Why Java? Naming Conventions. Classes. COMP9024: Data Structures and Algorithms

Computational Expression

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Fundamental Java Syntax Summary Sheet for CISC124, Fall Java is Case - Sensitive!

CSE 143 Au03 Midterm 2 Sample Solution Page 1 of 7

Using Java Classes Fall 2018 Margaret Reid-Miller

Assignment 5: MyString COP3330 Fall 2017

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Review. Single Pixel Filters. Spatial Filters. Image Processing Applications. Thresholding Posterize Histogram Equalization Negative Sepia Grayscale

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

ARG! Language Reference Manual

CS2141 Software Development using C/C++ C++ Basics

Last Time. Strings. Example. Strings. Example. We started talking about collections. Strings, Regex, Web Response

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Strings

Windows File I/O. Files. Collections of related data stored on external storage media and assigned names so that they can be accessed later

Eng. Mohammed Abdualal

Industrial Programming

Lesson:9 Working with Array and String

Chapter 11. Data Files The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

String related classes

CS112 Lecture: Characters and Strings

Transcription:

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. By Halkawt Rajab Hussain 2016-04-02

String and files: String declaration and initialization. Strings and Char Arrays: Properties And Methods. File creation, insertion, modification and deletion. 11/22/2016 1

A string is a sequence of characters stored in a certain address in memory. String keyword to declare a string variable. The string keyword is an alias for the System.String class. You can create string object using one of the following methods: 1. By assigning a string literal to a String variable. string fname, lname; fname = "Rowan"; lname = "Atkinson"; string fullname = fname + lname; Console.WriteLine("Full Name: 0", fullname); 2. By using a String class constructor. char[] letters = 'H', 'e', 'l', 'l','o' ; string greetings = new string(letters); Console.WriteLine("Greetings: 0", greetings); 11/22/2016 2

3. By using the string concatenation operator (+). string s1= ABCD ; string s2= 1234 ; string s3= s1 + s2; Console.WriteLine("Full Name: 0", s3); 4. By retrieving a property or calling a method that returns a string. string[] sarray = "Hello", "From", "Tutorials", "Point" ; string message = String.Join(" ", sarray); Console.WriteLine("Message: 0", message); 5. By calling a formatting method to convert a value or an object to its string representation. DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format("Message sent at 0:t on 0:D", waiting); Console.WriteLine("Message: 0", chat); 11/22/2016 3

Strings and Char Arrays: Strings are very similar to the char arrays (char[]), but unlike them, they cannot be modified. Like the arrays, they have properties such as Length, which returns the length of the string and allows access by index. Example string str = "abcde"; char ch = str[1]; // ch == 'b' str[1] = 'a'; // Compilation error! ch = str[50]; // IndexOutOfRangeException Example string message = "This is a sample string message."; Console.WriteLine("message = 0", message); Console.WriteLine("message.Length = 0", message.length); for (int i = 0; i < message.length; i++) Console.WriteLine("message[0] = 1", i, message[i]); 11/22/2016 4

String Properties And Methods: Properties Example String s= abcdef ; Console.WriteLine(s[ 3]); Console.WriteLine(s.Length); 11/22/2016 5

String Properties And Methods: Methods The String class has numerous methods that help you in working with the string objects. No. 1 2 3 4 5 Methods public static int Compare(string stra, string strb) Compares two specified string objects and returns an integer that indicates their relative position in the sort order public static int Compare(string stra, string strb, bool ignorecase )Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true. public static string Concat(string str0, string str1) Concatenates two string objects. public static string Concat(string str0, string str1, string str2) Concatenates three string objects. public static string Concat(string str0, string str1, string str2, string str3) Concatenates four string objects. 11/22/2016 6

No 6 7 8 9 10 11 12 Methods public bool Contains(string value) Returns a value indicating whether the specified String object occurs within this string. public static string Copy(string str) Creates a new String object with the same value as the specified string. public void CopyTo(int sourceindex, char[] destination, int destinationindex, int count) Copies a specified number of characters from a specified position of the String object to a specified position in an array of Unicode characters. public bool EndsWith(string value) Determines whether the end of the string object matches the specified string public bool Equals(string value) Determines whether the current String object and the specified String object have the same value. public static bool Equals(string a, string b) Determines whether two specified String objects have the same value. public static string Format(string format, Object arg0) Replaces one or more format items in a specified string with the string representation of a specified object. 11/22/2016 7

No 13 14 15 16 17 18 Methods public int IndexOf(char value) Returns the zero-based index of the first occurrence of the specified Unicode character in the current string. public int IndexOf(string value) Returns the zero-based index of the first occurrence of the specified string in this instance. public int IndexOf(char value, int startindex) Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting search at the specified character position. public int IndexOf(string value, int startindex) Returns the zero-based index of the first occurrence of the specified string in this instance, starting search at the specified character position. public int IndexOfAny(char[] anyof) Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. public static string Join(string separator, params string[] value) Concatenates all the elements of a string array, using the specified separator between each element. 11/22/2016 8

No 19 20 21 22 23 24 Methods public static string Join(string separator, string[] value, int startindex, int count) Concatenates the specified elements of a string array, using the specified separator between each element. public int LastIndexOf(char value) Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object. public int LastIndexOf(string value) Returns the zero-based index position of the last occurrence of a specified string within the current string object. public string Remove(int startindex)removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string. public string Remove(int startindex, int count) Removes the specified number of characters in the current string beginning at a specified position and returns the string. public string Replace(char oldchar, char newchar) Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string 11/22/2016 9

No 25 26 27 28 29 30 Methods public string Replace(string oldvalue, string newvalue) Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string. public string[] Split(params char[] separator) Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. public string[] Split(char[] separator, int count) Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return. public bool StartsWith(string value) Determines whether the beginning of this string instance matches the specified string. public char[] ToCharArray() Returns a Unicode character array with all the characters in the current string object. public char[] ToCharArray(int startindex, int length) Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length. 11/22/2016 10

No 31 32 33 Methods public string ToLower() Returns a copy of this string converted to lowercase. public string ToUpper() Returns a copy of this string converted to uppercase. public string Trim() Removes all leading and trailing white-space characters from the current String object. 11/22/2016 11

Example/ Comparing strings using System; namespace StringApplication class StringProg static void Main(string[] args) string str1 = "This is test"; string str2 = "This is text"; if (String.Compare(str1, str2) == 0) Console.WriteLine(str1 + " and " + str2 + " are equal."); else Console.WriteLine(str1 + " and " + str2 + " are not equal."); Console.ReadKey() ; 11/22/2016 12

Example/ String Contains String: using System; namespace StringApplication class StringProg static void Main(string[] args) string str = "This is test"; if (str.contains("test")) Console.WriteLine("The sequence 'test' was found."); Console.ReadKey() ; 11/22/2016 13

Example/ Getting a Substring: using System; namespace StringApplication class StringProg static void Main(string[] args) string str = "Last night I dreamt of San Pedro"; Console.WriteLine(str); string substr = str.substring(23); Console.WriteLine(substr); 11/22/2016 14

Example/ Joining Strings: using System; namespace StringApplication class StringProg static void Main(string[] args) string[] starray = new string[]"down the way nights are dark", "And the sun shines daily on the mountain top", "I took a trip on a sailing ship", "And when I reached Jamaica", "I made a stop"; string str = String.Join("\n", starray); Console.WriteLine(str); 11/22/2016 15

File: A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream. The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation). C# I/O Classes The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc. 1. File creation: 11/22/2016 16

The following table shows some commonly used non-abstract classes in the System.IO namespace: 11/22/2016 17

The FileStream Class The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream. You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows: FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>); File Creation, Insertion, Modification and Deletion: we create a FileStream object F for creating a file named sample.txt as shown: FileStream F = new FileStream("sample.txt", FileMode.Create, FileAccess.Write, FileShare.Read); 11/22/2016 18

using System; using System.IO; namespace FileIOApplication class Program static void Main(string[] args) FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite); for (int i = 1; i <= 20; i++) F.WriteByte((byte)i); F.Position = 0; for (int i = 0; i <= 20; i++) Console.Write(F.ReadByte() + " "); F.Close(); Console.ReadKey(); 11/22/2016 19

Example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class. Each text line is stored into the string line and displayed on the screen. int counter = 0; string line; System.IO.StreamReader file = new System.IO.StreamReader( D:\\test.txt"); while((line = file.readline())!= null) Console.WriteLine (line); counter++; file.close(); Console.ReadLine(); 11/22/2016 20

Example Read Text File into String Array (with StreamReader) using System.IO; class Program static void Main(string[] args) // Read every line in the file. using (StreamReader reader = new StreamReader("file.txt")) string line; while ((line = reader.readline())!= null) // Do something with the line. string[] parts = line.split(','); 11/22/2016 21

Example Read First Line in file file.txt using StreamReader. using System; using System.IO; class Program static void Main() // // It will free resources on its own. // string line; using (StreamReader reader = new StreamReader("file.txt")) line = reader.readline(); Console.WriteLine(line); 11/22/2016 22

Example Write two Lines to file file.txt using StreamWriter. using (StreamWriter writer = new StreamWriter( file.txt")) writer.write("word "); writer.writeline("word 2"); writer.writeline("line"); Append text. It is easy to append text to a file with StreamWriter. using (StreamWriter writer = new StreamWriter("C:\\log.txt", true)) writer.writeline("important data line 1"); using (StreamWriter writer = new StreamWriter("C:\\log.txt", true)) writer.writeline("line 2"); 11/22/2016 23

File.ReadAllText: Example Read all text file at one time. File.ReadAllLines: string value1 = File.ReadAllText("C:\\file.txt"); Console.WriteLine("--- Contents of file.txt: ---"); Console.WriteLine(value1); Read all the lines from a file and place them in an array. string[] lines = File.ReadAllLines("file.txt"); foreach (string line in lines) // Do something with the line. if (line.length > 80) // Important code. 11/22/2016 24

File.WriteAllLines. We can write an array to a file. Example string[] stringarray = new string[] "cat", "dog", "arrow" ; File.WriteAllLines("file.txt", stringarray); File.WriteAllText. A simple method, File.WriteAllText receives two arguments. File.WriteAllText("C:\\perls.txt", "Dot Net Perls"); 11/22/2016 25

File.Delete: using System.IO; class Program static void Main() TryToDelete("Word.doc"); static bool TryToDelete(string f) try // A. // Try to delete the file. File.Delete(f); return true; catch (IOException) // B. // We could not delete the file. return false; 11/22/2016 26

Thanks Any Questions 11/22/2016 27