Содержание:
- Lesson # 11. Theory
- Chars and Strings
- Declaring and Initializing Strings
- String «modification»
- Most common Escape characters within the stringsVerbatim strings
- Substring, Replace and IndexOf methods of string type
- Converting a string to an array: splitting strings
- Accessing Individual Characters
- How to change particular char inside a String
- Labs and Tasks
Lesson # 11. Theory
Lecture in pdf format
Chars and Strings
- To output the char we must surround it by the single quotes:
- Or we can use the variables of char type to store some symbol:
- A string is an object of type String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects.
- To output the string we must use double quotes:
- Or we can use the variables of string type to store some text:
Console.WriteLine('A'); |
char symb = 'A'; Console.WriteLine(symb); |
Console.WriteLine("Good Day"); |
string phrase = "Good Day"; Console.WriteLine(phrase); //Good Day Console.WriteLine(phrase[1]);// o |
Declaring and Initializing Strings
There are some ways of declaring and initialization strings:
// Declare without initializing. string str1; // Initialize to null. string str2 = null; // Initialize as an empty string: string str3 = ""; // Or better use the Empty constant instead of the literal "". string str3 = System.String.Empty; // Initialize with a regular string literal: string str4= "Microsoft Visual Studio"; // Initialize with a verbatim string literal: string str5= @"Microsoft Visual Studio"; // Or you can use System.String: System.String greeting = "Hello World!"; // In local variables (i.e. within a method body) you can use implicit typing: var temp = "I'm Ok"; // Use a const string to prevent 'str6' from // being used to store another string value. const string str6 = "I'm fine!"; // Use the String constructor only when creating // a string from a char*, char[], or sbyte*. See // System.String documentation for details. char[] letters = { 'A', 'B', 'C' }; string alphabet = new string(letters); Console.WriteLine(alphabet); // ABC |
String «modification»
- Concatenation means taking one string and an appending it onto the end of another string.
- The
+=
(Concatenation) operator creates a new string that contains the combined contents. - If you create a reference to a string, and then «modify» the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified:
string s1 = "A string is more "; string s2 = "than the sum of its chars."; // Concatenate s1 and s2. This actually creates a new // string object and stores it in s1, releasing the // reference to the original object. s1 += s2; System.Console.WriteLine(s1); // Output: A string is more than the sum of its chars. |
string s1 = "Hello "; string s2 = s1; s1 += "World"; System.Console.WriteLine(s2); //Output: Hello |
Most common Escape characters within the strings
Verbatim strings
Escape characters are special characters which are used in a c# string.
- Escape characters provided by C#:
- In c-sharp we have a kind of string that we call verbatim string. With a verbatim string we don’t have to use double backslashes when we need to use the slashes inside our text. We can simply prefix our string with an
@
sign and as a result we can get rid of all these double backslashes and just
use a single backslash. - When should we use Verbatim strings:
- when the string text contains backslash characters;
- to initialize multiline strings;
- when we have a quotation mark inside a string.
// Using Tab string columns = "Column 1\tColumn 2\tColumn 3"; //Output: Column 1 Column 2 Column 3 // New Line string rows = "Row 1\r\nRow 2\r\nRow 3"; /* Output: Row 1 Row 2 Row 3 */ //if we want to use a quotation mark, we use back slash: Console.WriteLine("I read the letter \"R\" in the text"); \\ I read the letter "R" in the text string title = "\"The \u00C6olean Harp\", by Samuel Taylor Coleridge"; //Output: "The Æolean Harp", by Samuel Taylor Coleridge |
string filePath = @"C:\Users\scoleridge\Documents\"; //Output: C:\Users\scoleridge\Documents\ string text = @"My pensive SARA ! thy soft cheek reclined Thus on my arm, most soothing sweet it is To sit beside our Cot,..."; /* Output: My pensive SARA ! thy soft cheek reclined Thus on my arm, most soothing sweet it is To sit beside our Cot,... */ string quote = @"Her name was ""Sara."""; //Output: Her name was "Sara." |
Substring, Replace and IndexOf methods of string type
- There are many standard methods in c# within a
string
type. We need to put a dot after the variable, and we have access to all the methods:
phrase....
string str = "Visual C# Education"; Console.WriteLine(str.Substring(7, 2)); // Output: "C#" Console.WriteLine(str.Replace("C#", "C++")); // Output: "Visual C++ Express" // Location of position of some character: // Index values are zero-based int index = str.IndexOf("C"); // Output: 7 // if there is no such character: Console.WriteLine(str.IndexOf ('z')); // Output negative 1: -1 |
Console.WriteLine(phrase.ToUpper()); |
Console.WriteLine(phrase.Contains("z")); // Output: False |
Converting a string to an array: splitting strings
- The following code example demonstrates the ability to parse a string using the
String.Split
method. The method works by returning an array of strings, in which each element represents a word.Split
method accepts an array of characters as input, specifying which characters should be used as delimiters. This example uses spaces, commas, periods, colons, and tabs. An array containing these delimiters is passed toSplit
method, and each word in the sentence is output separately using the resulting array of strings.
char delimiter = ' '; string text = "How do you do"; Console.WriteLine($"Initial text: '{text}'" ); string[] words = text.Split(delimiter); Console.WriteLine($"words in the text:{words.Length} "); foreach (string s in words) Console.WriteLine(s); |
Result:
Initial text: 'How do you do' words in the text:4 How do you do
char[] delimiterChars = { ' ', ',', '.', ':', '\t' }; string text = "one\ttwo three:four,five six seven"; Console.WriteLine($"Initial text: '{text}'" ); string[] words = text.Split(delimiterChars); Console.WriteLine($"words in the text:{words.Length} "); foreach (string s in words) Console.WriteLine(s); |
Result:
Initial text: 'one two three:four,five six seven' words in the text:7 one two three four five six seven
Example: Enter a text string. Print words in which the first letter occurs at least one more time.
string s = "wow,this is google"; string[] words = s.Split(' ', '.', ','); foreach (string word in words) { char c = word[0]; bool flag = false; int i = 1; while (i < word.Length & !flag) { if (word[i] == c) flag = true; i++; } if (flag) Console.WriteLine(word); } Console.ReadKey(); |
Accessing Individual Characters
- String consists of chars. To acquire a read-only access to individual characters within the string and ptint them out you can use array notation with an index value (use index of the character, starting with 0):
s[i]
– for access toi
-th char of ss.Length
– length of a string (how many characters there is inside our string)
Use for
loop:
var s = "Computer"; for (var i=0; i < s.Length; i++) Console.Write($"{s[i]} "); // Output: C o m p u t e r |
Use foreach
loop:
var s = "Computer"; foreach (var c in s) Console.Write($"{c} "); // Output: C o m p u t e r |
How to change particular char inside a String
- Strings in C# are immutable, it means that we can’t type the following code:
s[i]='a';
- Characters are decorated with single quotation marks.
- To change the value of a particular char within the string we can use
Substring
method: - You can use a
StringBuilder
object to modify the individual chars: - Creating of StringBuilder object:
- Using console to input and output the values:
StringBuilder
is a class that represents a mutable string. It makes it really easy and fast to create a string and modify it on the fly, but unlike thestring
class it’s not optimized for search. So it doesn’t have methods likeindexOf
orlastIndexOf
, etc.- Instead
StringBuilder
class provides some useful methods for manipulating strings: Append
— to add something to the end of a string;Insert
— to add something at the given index;Remove
— to remove something from the string;Replace
— to replace a character or a string.
var str = "abcdefghijjklmnopqrstuvwxy"; str = 'Z' + str.Substring(1); Console.WriteLine(str); // output: Zbcdefghijjklmnopqrstuvwxy |
string phrase = "Good Day"; Console.WriteLine(phrase.Substring(5)); // Output: 'Day' Console.WriteLine(phrase.Substring(5,2)); // how many characters we are going to grab, Output: 'Da' |
using System.Text; // this directive should be used //... var str = "Group roxette"; var sb = new StringBuilder(str); sb[6] = 'R'; str = sb.ToString(); Console.WriteLine(str); // output: Group Roxette |
// 1) Empty string: StringBuilder sb = new StringBuilder(); // 2) String with an initial length: int n = 50; StringBuilder sb = new StringBuilder(n); // 3) String with an initial value: StringBuilder sb = new StringBuilder("qwerty"); |
// ReadLine() method: StringBuilder sb = new StringBuilder(Console.ReadLine()); // WriteLine() method: Console.WriteLine(sb); |
Labs and Tasks
string s1 = "first string value"; string s2 = "second string value"; // Concatenate s1 and s2, and save the result in the third variable string s3 = s1 + " " + s2; System.Console.WriteLine(s3); // first string value second string value |
Join
method concatenates the collection of members of type String, using the specified separator between each member. We have a comma as a separator
string[] arr = new string[] { "how", "do", "you", "do" }; string s = string.Join(",", arr); Console.WriteLine($"result is: {s}"); //result is: how,do,you,do |
To do:
1) Declare two variables of string type. The identificators of the variables should be
firstName
and lastName
. Assign some values to these variables. Output the values of the variables.Expected output:
Dasha Kuvshinkina
2) Declare another variable of a string type, name it fullName
, and assign to it a concatenation (+
) of two strings together with a whitespace between them. Print out the variables as it is given in the Expected output:
Expected output:
First name = Dasha, Last name = Kuvshinkina Fullname: Dasha Kuvshinkina
3) Output the sentence ‘My name is fullName
‘, using Format
method.
Expected output:
My name is Dasha Kuvshinkina
4) Create an array of a string type, initialize it with three names as the values for the elements. Output the values of the array elements, using the Join
method and comma (,
) as a separator between the names.
Expected output:
John,Helen,Mary
5) Output the text with a greeting and a path to a file, use a verbatim string.
Expected output:
Hi John Look into the following paths c:\folder1\folder2 c:\folder3\folder4
[Solution and Project name: Lesson_11Lab1
, file name L11Lab1.cs
]
✍ How to do:
- Create a new project with a name and filename as it is given in the task.
- Create a variable of string type, call it
firstName
. Assign it a value:
Task #1:
"Dasha";firstName =
WriteLine
method.VAR
keyword instead of string
, because compiler ‘knows’, that we have assigned this variable a type string. Change the code:var firstName="Dasha";
lastName
and assign it a value. Print the value out:var lastName="Kuvshinkina"; Console.WriteLine(lastName);
Task #2:
// Task 2 var fullName = firstName + " " + lastName;
Task #3:
format
method to output the text as it is in the result example:// Task 3 var myFullName = .Format("My name is {0} {1}", firstName, lastName); Console.WriteLine(myFullName);
Task #4:
Join
method :// Task 4 var names = new [3] {"John", "Ivan", "Mary"}; var formattedNames = .Join(",", names); Console.WriteLine(formattedNames);
Join
method concatenates the collection of members of type String, using the specified separator between each member. We have a comma as a separator
Task #5:
// we have\n
to create a new line, we have\
to print out '\' symbol var text="Hi John\nLook into the following paths\nc:\\folder1\\folder2\nc:\\folder3\\folder4";
// Task 5 var text = @"Hi John Look into the following paths c:\folder1\folder2 c:\folder3\folder4"; Console.WriteLine(text);
@
sign, then we put new lines where we had \n
and removed all the double backslashes..cs
to the moodle system.To do: Initialize a single-dimensional array with given string values, they are the names Ivan Ivanov, Peter Sidorov, Mike Nikitin, Irina Aleksandrova
. Output the greeting to all of the people, using only their first names from the array.
Make the task twice: the first time you have to use IndexOf
and Substring
methods at the same time, the second — you must use Split
method only.
Expected output:
Using IndexOf and Substring methods: Hello Ivan! Hello Peter! Hello Mike! Hello Irina! Using Split method: Hello Ivan! Hello Peter! Hello Mike! Hello Irina!
[Solution and Project name: Lesson_11Lab2
, file name L11Lab2.cs
]
✍ How to do:
- Create a new project with a name and filename as it is given in the task.
- Create an array of string type and initialize it with a given in the task fullnames:
new [] { "Ivan Ivanov", "Peter Sidorov", "Mike Nikitin", "Irina Aleksandrova" };[] fullNames =
new [fullNames.Length];[] firstNames =
fullNames
array has. We use the method Length
to get the number of the fullNames
array.0
to the position of the space character:P e t e r S i d o r o v 0 1 2 3 4 5
IndexOf
method. To iterate over the elements of the array it is better to use for
loop:for (var i = 0; i < fullNames.Length; i++) { var index = fullNames[i].IndexOf(' '); ... }
IndexOf
reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance.index
variable. You need to use the Substring
method to get the firstname and to display it with a word ‘Hello’:for (var i = 0; i < fullNames.Length; i++) { var index = fullNames[i].IndexOf(' '); firstNames[i] = fullNames[i].Substring(0, index); Console.WriteLine("Hello " + firstNames[i]+"!"); }
Substring
method retrieves a substring from the fullNames instance. The substring starts at a specified character (0 index) position and has a specified length (the value of index
variable, that is the oreder position of a space).Split
method. Type the following code within the Main
function, after the previous code:Console.WriteLine("Split method:"); for (var i = 0; i < fullNames.Length; i++) { firstNames = fullNames[i].Split(' '); Console.WriteLine("Hello " + firstNames[0]+"!"); }
Split
method creates an array of substrings by splitting the input string based on one or more delimiters, we have a space (' '
) as a delimiter..cs
to the moodle system.To do: A character is entered (the character value should be stored in a c
variable). There is a string s
containing exactly two characters c
. Find the substring between these two characters. Use string class (not StringBuilder).
Note 1: It is better to use Substring
, IndexOf
and LastIndexOf
methods.
Note 2: Create a method named BetweenChars
with two arguments, they are the string and the character. Inside the Main
function you must call this method twice with different values of the parameters.
Expected output:
Result for astra string and a char is: str Result for nana string and a char is: n
[Solution and Project name: Lesson_11Task1
, file name L11Task1.cs
]
To do: Create a program to check whether the text contains the s letter. Output true if the letter s
is found and false if it is not found.
Note 1: Make the program in different ways: 1) using Contains
method and 2) iterating through the string’s characters using loop.
Note 2: Probably you’ll need the boolean variable:
bool b = false; |
Note 3: To terminate the loop you can use the break
statement:
// when i gets 5 value, the loop is terminated for (int i = 1; i <= 100; i++) { if (i == 5) { break; } Console.WriteLine(i); } |
Expected output:
Result 1: The string 'hello' contains s: False Result 2: The string 'hello' contains s: False ++++++++++++++ Result 1: The string 'hello sir' contains s: True Result 2: The string 'hello sir' contains s: True
[Solution and Project name: Lesson_11Task2
, file name L11Task2.cs
]
To do: Create a program for counting the number of letters combination «ma
» in the text. It is not allowed to use any standart methods, make the program by iterating through the string’s characters.
Note 1: Create a function CountInText
to make a program. The function must have two arguments, they are the string with a text and the string with letters combination to look for.
Expected output:
The string 'hello world' contains 0 of 'ma' +++++++++++++++++++ The string 'my mammy is the best, ma-ma-ma' contains 4 of 'ma'
[Solution and Project name: Lesson_11Task3
, file name L11Task3.cs
]
To do: A string is given (assign it to s
variable). Remove everything between the first two characters ‘*
‘. If there are no such characters in the string, leave the string unchanged. If there is only one character *
in the string, remove everything starting from this character to the end of the string. Use string class (not StringBuilder).
Note 1: It is better to use Contains
, IndexOf
and Remove
methods. The IndexOf
method can have two parameters:
IndexOf(char value, int StartIndex)
Note 2: Create a method named RemoveBetweenChars
with two arguments, they are the string and the character (the *
character should be the default value for the parameter). Inside the Main
function you must call this method twice with different values of the parameters.
Expected output:
Result for ast*qqra* string and * char is: ast** Result for POW*EROFBULL string and * char is: POW
[Solution and Project name: Lesson_11Task4
, file name L11Task4.cs
]
To do: Ask the user to enter a string. Invert the inputted string.
Expected output:
Please enter the sentence: Hello world The inverted sentence is: dlrow olleH
[Solution and Project name: Lesson_11Lab3
, file name L11Lab3.cs
]
✍ How to do:
- Create a new project with a name and filename as it is given in the task.
- Include the following directive to use the StringBuilder class:
- Ask the user to input a sentence (the code has to be inside the
Main
method. of course):
using System.Text; |
Console.WriteLine("Please enter the sentence:");
StringBuilder sb = new StringBuilder(Console.ReadLine());
for
loop to iterate over the letters of the sentence. But we’ll need two counters for loop — one of them is to iterate from the beginning of the sentence, and the other — to iterate from the end of the sentence:// i counter - to start from the beginning, j - from the end for ( i = 0, j = sb.Length - 1; i < j; i++, j--) { ... }c; // to store the temporary value of the letter
c
variable of char type to store the temporary value of the letter:for (int i = 0, j = sb.Length - 1; i < j; i++, j--) { c = sb[i]; sb[i] = sb[j]; sb[j] = c; }
sb
variable. Print the result out:Console.WriteLine("The inverted sentence is:"); Console.WriteLine(sb);
.cs
to the moodle system.To do: Two strings are given. Add space characters to the shorter one so that their lengths become the same. Use StringBuilder class also.
Note 1: It is better to use Append
method.
Note 2: Create a method named AddSpaces
with two arguments, they are the string and the number of space characters to add.
Expected output:
string1=1234. string2=123456. result: string1=1234 . string2=123456.
[Solution and Project name: Lesson_11Task5
, file name L11Task5.cs
]
To do: A string S
is given that contains two numbers separated by a space, and the character C
that has a value of one of the following characters: +
, -
, *
(a sign of the math operation). Create a string containing the result of calculations due to the string S
and character C
, for example, '2+3=5
'.
Make three or four automatic tests.
Note: Create a method named Calculate
with two arguments, they are the S
string and C
character.
Expected output:
The string is: 4 5 The character is: + The result is: 4+5=9 +++++++++ The string is: 4 5 The character is: * The result is: 4*5=20
[Solution and Project name: Lesson_11Task6
, file name L11Task6.cs
]