Lesson # 11. Strings

Дата изменения: 7 мая 2020
Programming on c sharp in Microsoft Visual Studio. Creating and working with strings.

Lesson # 11. Theory

Chars and Strings

  • To output the char we must surround it by the single quotes:
  • Console.WriteLine('A');
  • Or we can use the variables of char type to store some symbol:
  • char symb = 'A'; 
    Console.WriteLine(symb);
  • 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:
  • Console.WriteLine("Good Day");
  • Or we can use the variables of string type to store some text:
  • string phrase = "Good Day"; 
    Console.WriteLine(phrase);

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);

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.
  • 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.
  • 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 = "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#:
  • // 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
  • 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.
  • 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.<code>...</code>
  • A substring is any sequence of characters that is contained in a string:
  • 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
  • Also we have:
  • converting to uppercase:
  • Console.WriteLine(phrase.ToUpper());
  • finding some substring:
  • Console.WriteLine(phrase.Contains("z")); // Output: False

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 to i-th char of s
  • s.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.
  • 1. Using Substring method of string type:
  • To change the value of a particular char within the string we can use Substring method:
  • 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'
    2. Using StringBuilder class
  • You can use a StringBuilder object to modify the individual chars:
  • var str = "Group roxette";
    var sb = new StringBuilder(str);
    sb[6] = 'R';
    str = sb.ToString();
    Console.WriteLine(str); // output: Group Roxette
  • Creating of StringBuilder object:
  • // 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");
  • Using console to input and output the values:
  • // ReadLine() method:
    StringBuilder sb = new StringBuilder(Console.ReadLine());
     
    // WriteLine() method:
    Console.WriteLine(sb);
  • 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 the string class it’s not optimized for search. So it doesn’t have methods like indexOf or lastIndexOf, 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.

Labs and Tasks

Lab 1. Using concatenation and verbatim strings
  
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.
  
Result example:

Dasha 
Kuvshinkina

2) Declare another string and assign to it a concatenation of two strings together with a whitespace between them.
 
Result example:

First name = Dasha, Last name = Kuvshinkina
Fullname:
Dasha Kuvshinkina

  
3) Output the sentence ‘My name is fullName‘, using Format method.
  
Result example:

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.
 
Result example:

John,Helen,Mary

  
5) Output the text with a greeting and a path to a file, use a verbatim string.
  
Result example:

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 file name as it is given in the task.
  • Task #1:

  • Create a variable of string type, call it firstName. Assign it a value:
  • string firstName = "Dasha";
    
  • Output the value of this variable, using WriteLine method.
  • Here we can use the VAR keyword instead of string, because compiler ‘knows’, that we have assigned this variable a type string. Change the code:
  • var firstName="Dasha";  
    
  • Create another variable called lastName and assign it a value. Print the value out:
  • var lastName="Kuvshinkina"; 
    Console.WriteLine(lastName);
    

      
    Task #2:

  • We’re going to concatenate three strings together (including whitespace string to separate two values). Declare another string and concatenate three strings together:
  • // Task 2
    var fullName = firstName + " " + lastName;
    
  • Output the result as it is in the example of the task.
  •  
    Task #3:

  • String class has many static methods. They’re accessible directly on the string class. We’re going to use the format method to output the text as it is in the result example:
  • // Task 3
    var myFullName = string.Format("My name is {0} {1}", firstName, lastName);
    Console.WriteLine(myFullName);
    
    Format method takes two arguments, the first one is a format string or a template and the other one consists of the arguments that are the values to supply to this template.

      
    Task #4:

  • Create an array of a string type and output it’s elements’ values, using the Join method :
  • // Task 4
    var names = new string[3] {"John", "Ivan", "Mary"};
    var formattedNames = string.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:

  • The task is to create a string that has multiple lines and has two paths to files. If we didn’t know what we could use verbatim strings we would have something like this:
  • // 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";
    
  • This string is very unreadable. Now we’re going to output this text using a verbatim string:
  • // Task 5
    var text = @"Hi John
    Look into the following paths
    c:\folder1\folder2
    c:\folder3\folder4";
    Console.WriteLine(text);
    
    We have prefixed it with an @ sign, then we put new lines where we had \n and removed all the double backslashes.
  • Run the application again and check the output.
  • Add comments with the text of the task and save the project. Download file .cs to the moodle system.

Lab 2. String methods
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 with names from the array, using only their first names. 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.

 
The result examples:

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 file name as it is given in the task.
  • Create an array of string type and initialize it with a given in the task fullnames:
  • string[] fullNames = new string[] { "Ivan Ivanov", "Peter Sidorov", "Mike Nikitin", "Irina Aleksandrova" };
    
  • Create one more array of string type to store the first names of given fullnames. You don’t need to set the values to the elements of the array, but you need to specify the number of its elements.
  • string[] firstNames = new string[fullNames.Length];
    
    There will be the same number of elements as the fullNames array has. We use the method Length to get the number of the fullNames array.
  • To get the firstname out of the fullname you have to take the first word, e.g. «Peter» from the fullname «Peter Sidorov». Or, in other words, to cut off the number of characters from 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  
    
  • To search for an order position (occurrences) of space character inside each of the elements of the array, use the 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(' ');
       ...
    }
    
    Method 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.
  • After, there the order position of the space is inside 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).
  • Run the application and check the output.
  • The same result we’re going to have using the 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]+"!");
          }
    
    The code splits a fullname phrase into an array of strings for each word. E.g. for the ‘Peter Sidorov’ fullname we have firstNames[0] = ‘Peter’ and firstNames[1] = ‘Sidorov’.
    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.
  • Run the application again and check the output.
  • Add comments with the text of the task and save the project. Download file .cs to the moodle system.

Task 1:

To do: A character is given (assign it to the variable c). 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 for the parameters.

The resulting example:

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]




Task 2: Methods and without them

To do: Create a program to check whether the text contains the letter s. 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.
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);
        }

  
The resulting example:

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]



Task 3:

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.

The resulting example:

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]



Task 4:

To do: A string is given (assign it to the variable s). 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. Method IndexOf can be of 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 for the parameters.

The resulting example:

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]


Lab 3. Using StringBuilder class
  
To do:  Ask the user to input a string. Invert the inputted string. 

Result example:

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 file name as it is given in the task.
  • Ask the user to input a sentence (the code has to be inside the Main method. of course):
  •  Console.WriteLine("Please enter the sentence:");
    
  • Create an instance of a StringBuilder class object. Initialize it with an entered value:
  • StringBuilder sb = new StringBuilder(Console.ReadLine());
    
  • To invert the sentence, we’re going to use the following algorithm: take the first letter of the entered sentence and swap it with the last one. After that, we take the second letter and swap it with the second from the end. The process will continue untill the taken letters meet each other.
  • Use 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:
  • char c; // to store the temporary value of the letter
    // i counter - to start from the beginning, j - from the end
    for (int i = 0, j = sb.Length - 1; i < j; i++, j--) 
       {
           ...
       }
    
  • Inside the loop we must swap the letters, using 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;
       }
    
  • After that, we have the inverted senstence inside sb variable. Print the result out:
  • Console.WriteLine("The inverted sentence is:");
    Console.WriteLine(sb);
    
  • Run the application again and check the output.
  • Add comments with the text of the task and save the project. Download file .cs to the moodle system.


Task 5:

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.

The resulting example:

string1=1234.  string2=123456.
result: string1=1234  .  string2=123456.

  
[Solution and Project name: Lesson_11Task5, file name L11Task5.cs]





Task 6:

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 string S and the C character.

The resulting example:

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]


Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

*
*


Вставить формулу как
Блок
Строка
Дополнительные настройки
Цвет формулы
Цвет текста
#333333
Используйте LaTeX для набора формулы
Предпросмотр
\({}\)
Формула не набрана
Вставить