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