• No results found

Practice 2 String Type

N/A
N/A
Protected

Academic year: 2020

Share "Practice 2 String Type"

Copied!
16
0
0

Loading.... (view fulltext now)

Full text

(1)

Simple C# Program Using

String

Type

(Practice Class)

Subjects:

Representation of textual data

System.String Type

Special (escape) characters

(2)

Representation of textual data

C# textual data is represented by the intrinsic string and char keywords, which are simple shorthand notations for System.String and System.Char, both of which are Unicode under the hood. A string represents a contiguous set of characters (e.g.,

(3)

System.String Type

System.String provides a number of methods you would expect from such a utility class, including methods that return the length of the character data, find substrings within the current string, convert to and from uppercase/lowercase, and so forth.

String member Meaning in life

Length This property returns the length of the current string. Compare() This method compares two strings.

Contains() This method determines whether a string contains a specific substring.

Equals() This method tests whether two string objects contain identical character data.

Format() This method formats a string using other primitives (e.g., numerical data, other strings) and the {0} notation.

Insert() This method inserts a string within a given string.

PadLeft() These methods are used to pad a string with some characters. PadRight()

Remove() Use these methods to receive a copy of a string, with modifications (characters removed or replaced).

Replace()

Split() This method returns a String array containing the substrings in this instance that are delimited by elements of a specified Char or String array.

Trim() This method removes all occurrences of a set of specified characters from the beginning and end of the current string.

ToUpper() These methods create a copy of the current string in uppercase or lowercase format, respectively.

ToLower()

(4)

System.String Type

static void BasicStringFunctionality() {

Console.WriteLine("=> Basic String functionality:"); string firstName = "Freddy";

Console.WriteLine("Value of firstName: {0}", firstName);

Console.WriteLine("firstName has {0} characters.", firstName.Length(); Console.WriteLine("firstName in uppercase: {0}", firstName.ToUpper()); Console.WriteLine("firstName in lowercase: {0}", firstName.ToLower()); Console.WriteLine("firstName contains the letter y?: {0}“,

firstName.Contains("y"));

Console.WriteLine("firstName after replace: {0}", firstName.Replace("dy", ""));

Console.WriteLine(); }

(5)

Special (escape) characters

Like in other C-based languages, C# string literals may contain various escape characters, which qualify how the character data should be printed to the output stream. Each escape character begins with a backslash, followed by a specific token.

Character Meaning in life

\' Inserts a single quote into a string literal. \" Inserts a double quote into a string literal.

\\ Inserts a backslash into a string literal. This can be quite helpful when defining file paths. \a Triggers a system alert (beep). For console programs, this can be an audio clue to the user. \n Inserts a new line.

\r Inserts a carriage return.

\t Inserts a horizontal tab into the string literal.

static void EscapeChars() {

Console.WriteLine("=> Escape characters:\a"); string strWithTabs = "Model\tColor\tSpeed\tPet Name\a ";

Console.WriteLine(strWithTabs);

Console.WriteLine("Everyone loves \"Hello World\"\a ");

Console.WriteLine("C:\\MyApp\\bin\\Debug\a ");

// Adds a total of 4 blank lines (then beep again!).

Console.WriteLine("All finished.\n\n\n\a "); Console.WriteLine();

(6)

Manipulations with strings

(7)

Task List

1) Create the simplest C# console project.

2) Define array of strings using shortest possible style of string definition. Array should contain three strings: “Yabba”, “Dabba”, “Dooooo”.

3) Join all strings with using “ !!! ” separator (System.String methods for using

String.Join(“separator”, nameOfString);).

4) Create correct version of exclamation with addition of “!!!!!!!!” to the end of string.

5) Create string “It is not easy for me to use strings with “escape” characters !!!”.

6) Check for presence of “hard” and “easy” words in the previous-defined string (method Contains(“some string)).

7) If “easy” is present and “hard” is absent, replace word “easy” with “hard” word (method Replace("someString1", "someString2")).

For all steps you should output the results using Console.WriteLine method.

(8)

A C# program consists of one or more type declarations. The types in a program can be declared in any order. In the SimpleProgram example, only a class type is declared.

A namespace is a set of type declarations associated with a name. SimpleProgram

uses two namespaces. It creates a new namespace called Simple, in which it declares its type (class Program), and uses the Console class defined in a namespace called

System.

(9)
(10)

Completing the Task

2) Define array of strings using shortest possible style of string definition. Array should contain three strings: “Yabba”, “Dabba”, “Dooooo”.

// Array initialization syntax using the new keyword.

string[] words = new string[] { "Yabba", "Dabba", "Dooooo" };

// Array initialization syntax without using the new keyword. string[] words = { "Yabba", "Dabba", "Dooooo" };

Declaration Initialization Name

(11)

Completing the Task

3) Join all strings with using “!!! ” separator (System.String methods for using

String.Join(“separator”, nameOfString);).

String.Join Method concatenates the elements of an object array, using the specified separator between each element.

//Joining: first argument is a separator, second - name of //array of strings

string s1 = String.Join("!!! ", words);

(12)

The

WriteLine()

method

You may have noticed that the WriteLine() construct is nothing more than a method call that’s invoked by a Console class:

Console.WriteLine(“this is a method call”);

WriteLine() is one of many predefined methods provided by the .NET Framework library. The Console predefined class refers to the application console (also known as the command prompt or command window). The argument to the WriteLine()method is a single string. The + operator enables the programmer to combine strings, or to combine a string and an intrinsic variable, before the sum is passed to WriteLine():

string s = “Sarah”;

Console.WriteLine(“My name is “ + s + “ and my age is “ + 3);

(13)

The

WriteLine()

method

A second form of WriteLine() provides a more flexible set of arguments:

Console.WriteLine(“My name is {0} and my age is {1}.”,

“Sarah”, 3);

(14)

Completing the Task

5) Create string “It is not easy for me to use strings with “escape” characters !!!”.

6) Check for presence of “hard” and “easy” words in the previous-defined string (method Contains(“some string)).

String.Contains Method returns a value indicating whether a specified substring occurs within this string.

// This example demonstrates the String.Contains() method

string s1 = “The quick brown fox jumps over the lazy dog”; string s2 = “fox”;

bool b;

b = s1.Contains(s2);

(15)

Completing the Task

7) If “easy” is present and “hard” is absent, replace word “easy” with “hard” word (method Replace("someString1", "someString2")).

String.Replace Method (String, String) returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

// Correct the spelling of "document".

string errString = "This docment uses 3 other docments to docment the docmentation";

(16)

Completing the Task

References

Related documents

Online game-based formative assessment tools: Quizlet, Quizizz, and Kahoot Some ideas on Assessment on the Virtual Environment?. Final Thoughts on Assessment on the

Read characters representing a floating point number from string data, convert them to a floating point number;. the character stream is terminated by a blank; any other

Figure 4 shows the stray current: operating currents split among the PEN conductors, the cable screens and the equipotential conductor in a TN-C system according to Kirchhoff’s

19.7 Finding Characters in a string 19.8 Replacing Characters in a string 19.9 Inserting Characters into a string 19.10 Conversion to C-Style char * Strings 19.11 Iterators..

• Escape sequences are used to represent certain special characters within string.. literals and

You finally expand this out a pool by declaring a string variable In C strings are stored as key character pointers or const char const char theStringYo.. String Pointers in

[r]

All mobile food vehicles must apply for a fire safety permit issued by the Chicago Fire Department (CFD) if they utilize the following: a gasoline, diesel, or propane supplied