1 Text Files and String Processing. 2 The Char Struct For documentation Help > Search. Look for:...

Preview:

Citation preview

1

Text Files and String Processing

2

The Char Struct

For documentation Help > Search. Look for: Char

Structure Filtered by:

Language: Visual C# Technology: .NET Development Content Type: Documentation & Articles

Double click on Char Structure in Search Results.

3

The Char Struct

The Char value type represents a Unicode character (aka Unicode code point)

Implemented as a 16-bit number ranging in value from hexadecimal 0x0000 to 0xFFFF.

See http://www.unicode.org/

4

The Char Struct

Examples (from the help page)

char chA = 'A';

char ch1 = '1';

string str = "test string";

Examples of char methods on the next slide use these examples as arguments.

Note: Single quotes around char literal.

Note: Double quotes around string literal.

5

Static Methods of the Char Struct

Console.WriteLine(chA.CompareTo('B')); // Output: "-1"

Console.WriteLine(chA.Equals('A')); // Output: "True"

Console.WriteLine(Char.GetNumericValue(ch1)); // Output: "1"

Console.WriteLine(Char.IsControl('\t')); // Output: "True"

Console.WriteLine(Char.IsDigit(ch1)); // Output: "True"

Console.WriteLine(Char.IsLetter(',')); // Output: "False"

Console.WriteLine(Char.IsLower('u')); // Output: "True"

Console.WriteLine(Char.IsNumber(ch1)); // Output: "True"

Console.WriteLine(Char.IsPunctuation('.')); // Output: "True"

Console.WriteLine(Char.IsSeparator(str, 4)); // Output: "True"

Console.WriteLine(Char.IsSymbol('+')); // Output: "True"

Console.WriteLine(Char.IsWhiteSpace(str, 4)); // Output: "True"

Console.WriteLine(Char.Parse("S")); // Output: "S"

Console.WriteLine(Char.ToLower('M')); // Output: "m"

Console.WriteLine('x'.ToString()); // Output: "x"

6

The String Class

For documentation search for String Class Help, Search for: "String Class" Filtered by:

Language: Visual C# Technology: .NET Development Content Type: Documentation & Articles

Double click on String Class in Search Results.

7

Finding Documentation

String Class Documentation

9

The String Class

Class String vs "strings"

A String object is a sequential collection of System.Char structs that represents a string.

The value of the String is the content of the sequential collection, and the value is immutable.

Methods that appear to modify a String actually return a new String containing the modification.

10

String vs string

As types, System.String and string are interchangeable. In C# string is an alias for System.String.

We normally don’t need to prefix String with System because most C# programs have the line

using System;

11

String vs string

static void Main(string[] args)

{

string s = "This is a string";

Console.WriteLine(s);

String S = "This is a String";

Console.WriteLine(S);

Console.ReadLine();

}

12

String Literals

Character strings enclosed in double quotes are string literals. Compare to C/C++

String S1 = "This is a String";

Some characters have special interpretation in string literals: \t is replaced by a tab character \" is replaced by a quote character

(rather than ending the string) \\ is replaced by a backslash character

13

String Literals

If you don’t want escape character processing, place @ in front of the quoted string. Called a verbatim literal.

S1 = @"This is a string with a backslash \"

This is frequently done in Microsoft examples. Especially nice for Windows file path strings, which

include backslash characters.

14

String Literal Documentation

15

String Literal Documentation

16

String Operations

The String class provides a rich set of operations: Substring Concatination Length Comparison

If you need to do it, there is probably a built-in operation for it.

Click on the “Methods” link in the documentation page for String Class.

String Methods Documentation

18

Example: Converting to Upper Case

static void Main(string[] args)

{

String S1 = @"This is a string with a backslash \";

Console.WriteLine(S1);

Console.WriteLine("Converting S1 to Upper Case");

S1.ToUpper();

Console.WriteLine("Here is the result:");

Console.WriteLine(S1);

Console.ReadLine();

}

Caution: This code is (intentionally) incorrect.

19

Converting to Upper Case

What’s wrong here?

20

String Function Used Correctly

static void Main(string[] args) { String S1 = @"This is a string with a backslash \";

Console.WriteLine (S1);

Console.WriteLine ("Converting S1 to Upper Case");

String S2 = S1.ToUpper();

Console.WriteLine ("Here is the result:"); Console.WriteLine (S2);

Console.ReadLine(); }

21

String Function Used Correctly

22

String Operations

Ordinal acts on the numeric value of each Char object

Linguistic acts on the value of the String taking into

account culture-specific casing, sorting, formatting, and parsing rules.

Ordinal operations use the binary value of the chars Linguistic operations execute in the context of an

explicitly declared culture or the implicit current culture.

Typically work as you would expect them to.

23

Example: Cuture Sensitive Compare

http://msdn.microsoft.com/en-us/library/84787k22.aspx

24

Example: Numeric Compare

http://msdn.microsoft.com/en-us/library/af26w0wa.aspx

25

Comparing Stringsclass Program

{

static void Main(string[] args)

{

string S1 = @"This is a string with a backslash \";

Console.WriteLine(S1);

Console.WriteLine("Converting S1 to Upper Case");

string S2 = S1.ToUpper();

Console.WriteLine("Here is the result:");

Console.WriteLine(S2);

int i1 = String.Compare(S1, S2);

Console.WriteLine("Compare(S1, S2) = {0}", i1);

int i2 = String.CompareOrdinal(S1, S2);

Console.WriteLine("CompareOrdinal(S1, S2) = {0}", i2);

Console.ReadLine();

}

26

Comparing Strings

27

Using Operators

if (S1 == S2)

{

Console.WriteLine("S1 and S2 are equal");

}

else

{

Console.WriteLine("S1 and S2 are not equal");

}

28

Using Operators

29

Using Operators

if (S1 < S2)

{

Console.WriteLine("S1 is less than S1");

}

else

{

Console.WriteLine("S1 is not less than S1");

}

30

Using Operators

We can use the == operator with strings.

But not < and >.

Remember that == for reference types normally checks if the operands are references to the same object. Class string overrides the operator inherited

from class System.Object. Compares the contents of the operands.

31

Operations on Strings

All numeric types provide a Parse static method that converts a string into the numeric value.

String strZip; // Zip code as stringint intZip; // Zip code as integer...intZip = int.Parse(strZip);

Will throw an exception if the string is not the representation of a number of the specified type.

32

tryParse

Numeric types also have a tryParse method that will not throw an exception when the string is not a valid number.

static void Main(string[] args)

{

String strZip = Console.ReadLine();

int intZip;

if (int.TryParse(strZip, out intZip))

{

Console.WriteLine(strZip + " is a valid integer");

}

else

{

Console.WriteLine(strZip + " is not a valid integer");

}

}

33

Parsing Integers

34

Comma Separated Values

Common way to represent structured data in a text file.

Example:Doe,John,1234 Oak

St.,Marion,OH,22333

Frequently used as interchange format for spreadsheet and database programs.

35

The String.Split Method

For documentation Help > Search. Look for: Split

Double click on “String.Split Method” in Search Results.

36

String.Split Example

static void Main(string[] args){ string words = "one,two,three,four"; string[] split;

split = words.Split(',');

foreach (string s in split) { Console.WriteLine(s); } Console.ReadLine();}

Note: Char

37

String.Split Example

38

static void Main(string[] args){ String[] fruits = {"apple", "orange", "grape", "pear"};

String result = String.Join ( ",", fruits);

Console.WriteLine (result); Console.ReadLine();}

The String.Join Method

Note: String, not char

39

The String.Join Method

40

Operations Producing Strings

Every class has a ToString() method

Inherited from Class object

Default is Namespace.ClassName

Should override the default in your own class definitions. Include a meaningful version in class

definition.

41

Example: Circle.ToString()

class Circle : Shape{ double radius;

public Circle(double radius_arg, String name_arg) : base (name_arg)

{this.radius = radius_arg;

}

public double Radius() { return radius; }

public override String ToString() { return "I am a Circle of radius " + radius.ToString() + " by the name of " + name; }}

End of Section

42

Text Files

For documentation Help > Search. Look for: text file i/o Filtered by:

Language: Visual C# Technology: .NET Development Content Type: Documentation & Articles

Double click on “Basic File I/O” in Search Results.

43

Writing a Text File

static void Main(string[] args){ String[] text_array = new String[4]; text_array[0] = "This is the first line"; text_array[1] = "This is the second line"; text_array[2] = "Line \t with \t some \t tabs"; text_array[3] = @"Line with a backslash \";

System.IO.StreamWriter Writer = new System.IO.StreamWriter (@"C:\test.txt");

foreach (String S in text_array) { Writer.WriteLine(S); }

Writer.Close(); Console.WriteLine (@"File C:\test.txt written"); Console.ReadLine();}

44

Running Text File Demo Program

45

Look at the File

46

Reading a Text File

using System.IO;

...

static void Main(string[] args)

{

String Input_Line; StreamReader Reader = new StreamReader(@"c:\test.txt");

while ((Input_Line = Reader.ReadLine()) != null)

{

Console.WriteLine(Input_Line);

}

Console.ReadLine();

}

47

Program Running

48

Summary

Class String is extraordinarily complex but we can usually ignore the complexity Typically will do what we expect. Provides built-in methods to do whatever we

need.

Reading and Writing sequential text files in C# is easy. “Open” operation is replaced by instantiating

a StreamReader or StreamWriter. Use that object to read or write the file one

line at a time. Be sure to call Close() method when finished.

End of Section

Recommended