C#. Type “string”. Function, properties, operations

Typestring“. Examples. Functions, properties, operations


Search other websites:

1. What are the main features of the type “string” in C#?

In C#, the built-in string data type supports Unicode character strings. For strings of type string, the following features can be distinguished:

  • any variable of type string is an object of the System.String class;
  • the type string is of reference type and not value type;
  • strings of type string are placed in the heap;
  • a variety of methods, properties, and operations can be applied to strings of type string;
  • a string of type string can be created using the new operator and without using this operator by assigning =;
  • the content of a object of string type cannot be changed.

An example of a literal string of type string:

"This is a text"


2. Ways to create an instance of type string

As you know, the string type is an alias of the System.String class, which has several constructors. Using these constructors, you can instantiate the string class. The following is an example of a program that demonstrates creating instances of type string in various ways.

using System;

namespace ConsoleApp1
  class Program
    static void Main(string[] args)
      // Ways to create an instance of type string
      // 1. Creating and initializing a string when declaring
      string s1 = "Hello";
      Console.WriteLine("s1 = {0}", s1);

      // 2. Creating a string from an array of type char[]
      char[] ArrayChar = { 'H', 'e', 'l', 'l', 'o' };
      string s2 = new string(ArrayChar);
      Console.WriteLine("s2 = {0}", s2);

      string s3 = new string(ArrayChar, 2, 3); // get part of the string
      Console.WriteLine("s3 = {0}", s3);

      // 3. Creating a string using the overloaded assignment operator =
      string s4;
      s4 = "Hello";
      Console.WriteLine("s4 = {0}", s4);

      // 4. Creating a string from one character
      string s5 = new string('+', 10); // character '+' - 10 times
      Console.WriteLine("s5 = {0}", s5);

      // 5. Verbatim strings
      string s6;
      s6 = @"C:\Programs\abc.txt"; // this is a verbatim string, @ is placed before the string
      Console.WriteLine("s6 = {0}", s6);          

The result of the program

s1 = Hello
s2 = Hello
s3 = llo
s4 = Hello
s5 = ++++++++++
s6 = C:\Programs\abc.txt


3. How to set the string into the variable of type string? Operation =

To do this, you need to use the assignment operator ‘=‘.

Way #1. The assignment after defining.

string s; // defining the variable
s = "This is a text"; // assignment the text

Way #2. Assignment during the definition (initialization of variable).

string s = "This is a text"; // initialization

Way #3. Using the method Copy().

s = string.Copy("This is a text"); // s = "This is a text"


4. How to determine, are two strings equal between themselves? Operation ==

The two strings can be compared by using operator “==“.

Code snippet, that defines an equality (inequality) of two strings:

string s1 = "Hello!";
string s2 = "Hello!";
bool f_equal;
if (s1 == s2)
    f_equal = true;
    f_equal = false;


5. How to compare two string of type string in lexicographical order? Method CompareTo()

In this case it is needed to use method CompareTo(). Method returns -1, 0 or 1. In the given example is shown the result of work the method.

string s1 = "abcd";
string s2 = "abcde";
int res;
res = s1.CompareTo(s2); // res = -1, (s1<s2)
res = s2.CompareTo(s1); // res = 1, (s2>s1)
s2 = s1; 
res = s1.CompareTo(s2); // res = 0, (s1==s2)
res = s2.CompareTo(s1); // res = 0


6. How combine two strings of type string? Method Concat(), operation +

Way #1 – method Concat().

string s1 = "Hello ";
string s2 = "world!";
string s3;
s3 = string.Concat(s1, s2); // s3 = "Hello world!"

Way #2 – using operator “+“.

string s1 = "Hello ";
string s2 = "world!";
string s3;
s3 = s1 + s2; // s3 = "Hello world!"


7. How copy one string into another string? Method Copy(), operation =

Way #1 – assignment operator.

string s1 = "My string";
string s2;
s2 = s1; // s2 = "My string"

Way #2 – method Copy().

string s1 = "My string";
string s2;
s2 = string.Copy(s1); // s2 = "My string"


8. Inserting a substring starting at the specified index. Method Insert()

To insert a substring need to use method Insert(). Method gets two parameters. First parameter is position of index in string, from which inserting is done (strarts with 0). Second parameter – text of the same string.

string s1 = "ABEF";
string s2;
s2 = s1.Insert(2, "CD"); // s2 = "ABCDEF"
s1 = "123";
s2 = s1.Insert(0, "555"); // s2 = "555123"

// Error!
// The specified argument is outside the allowable values
// s2 = s1.Insert(20, "33");

If set the index to out of range, then will be generated exception.


9. Finding and returning the index of the first occurrence of a substring in the given string. Method IndexOf()

This is realized by method IndexOf(). If substring is found in the string then method returns a position of first occurrence. Otherwise method returns -1. Method has the overloaded realizations.

string s = "Hello world!";
int index;
index = s.IndexOf("wor"); // index = 6
index = s.IndexOf("abc"); // index = -1

// another realization of IndexOf()
index = s.IndexOf("wor", 7); // index = -1 - search from position 7
index = s.IndexOf("wor", 0); // index = 6 - search from position 0

// search starts from specified index (3)
// and being verified the specified number of characters (5)
index = s.IndexOf("wo", 3, 5); // index = 6


10. Search the index of last occurrence of substring in the string by method LastIndexOf()

Method has several overloaded realizations. The index of last occurrence starts from 0.

string s = "bestprog.net";
int index;
index = s.LastIndexOf("prog"); // index = 4


11. How to define the length of string? Property Length

To define the length of string (number of characters) is used property Length.

string s = "bestprog.net";
int len;
len = s.Length; // len = 12
s = "";         // len = 0


12. Creating a string of predetermined width. Methods PadLeft() and PadRight()

Functions PadLeft() and PadRight() are used for creating the formatted string, in which the right positions and left positions are filled by spaces.

string s1 = "abc";
string s2;
s2 = s1.PadLeft(5); // s2 = " abc"
s2 = s1.PadLeft(2); // s2 = "abc"
s2 = s1.PadLeft(9); // s2 = "     abc"

// Error "Non-negative number required."
// s2 = s1.PadLeft(-2);

s2 = s1.PadRight(2); // s2 = "abc"
s2 = s1.PadRight(8); // s2 = "abc     "


13. Deleting the specified number of characters from string. Method Remove()

Method Remove() has two realizations. In the first realization method gets two parameters. In the second realization method gets one parameter.

Example #1. Method Remove() with two parameters.

string s1 = "0123456789";
string s2;
s2 = s1.Remove(3, 2); // s2 = "01256789"

In the example, function Remove() gets two parameters. First parameter is a position of index of string where deleting is done. Second parameter is number of characters which must be deleted.

Example #2. Realization with one parameter.

string s1 = "0123456789";
string s2;
s2 = s1.Remove(4); // s2 = "0123"

In this example function gets one parameter. This parameter defines a position from where characters will be deleted to the end of string.

If specify

s2 = s1.Remove(0);

then all string will be deleted.

Example #3. If you need to delete the last character in string then you need to write following code.

string s1 = "This is a text!";
string s2;
int len;
len = s1.Length;
s2 = s1.Remove(len-1); // s2 = "This is a text"


14. Replacing the characters in string. Method Replace()

Method Replace() has two realizations. First realization operates by strings. The second realization operates with type char.

Example #1. Using the Replace() function to replace one string to another string.

string s1 = "0123456789";
string s2;
s2 = s1.Replace("012", "ABC"); // s2 = "ABC3456789"

Example #2. Using the Replace() function to replace the character ‘0’ to the character ‘A’.

string s1 = "0123456789";
string s2;
s2 = s1.Replace('0', 'A'); // s2 = "A123456789"


15. How to select the substring in string. Method Substring()

Method Substring() has two realizations.

Variant #1. Selection the substring from given position to the end of string.

string s1 = "Automobile";
string s2;
s2 = s1.Substring(4); // s2 = "mobile

Variant #2. Selection the substring from given position (parameter #1) to the specified number of characters (parameter #2).

string s1 = "Automobile";
string s2;
s2 = s1.Substring(0, 4); // s2 = "Auto"


16. Converting the string which represented as number into the integer. Method Parse()

Parse() function allows to translate a string that consists of digits in an integer.

This function is useful if you need to get the number that has been entered from the keyboard and received as string. For example, entering from the TextBox control.

// string => int
string s = "389";
int i;
i = int.Parse(s);
i = int.Parse("-29"); // i = -29


17. Converting the integer into string. Method ToString()

Function ToString() converts an integer number into it’s string representation. For example, this function is useful, if you need to display the integer number on the form in the control Label.

// int => string
string s;
int i;
i = 230;
s = i.ToString(); // s = "230"


18. Converting string into the floating point number

When you convert string into corresponding real number, it is important to take into account the character encoding.

// string => double
double x;
string s;
s = "9.83";
x = double.Parse(s); // x = 9.83


19. Converting the floating point number into string
// double => string
double x;
string s;
x = -39.038;
s = x.ToString(); // s = "-39.038"


20. Converting the string into the value of bool type
// string => bool
bool b;
string s;
s = "true";
b = bool.Parse(s); // b = True


21. Persistence of strings. How to replace a character at a given position in a string: s [index] = c

In C#, the string type has one feature. A single character of a string is accessed in read mode. It is not possible to directly change the value of a character in a string.

The following code snippet

string s = "Hello world!";
s[6] = 'W'; // error!!! - character can only be read
char c;
c = s[6]; // c = 'w' - it works

in the line

s[6] = 'W';

will cause the compiler error

Property or indexer 'string.this[int]' cannot be assigned to -- it is read only

This means that the value of a character at a given position of a string of type string can only be read. To solve this problem, you can use (as an example) one of the proposed methods.

Mehtod 1. Using the Substring() and String() methods. When using this method, you need to check the index value for correctness. If the index value goes beyond the dimension of the string, an exception will occur.

// How to replace a character in a string at a given position: s[index]=c
// Method 1. Using methods Substring() and ToString().
// Input data:
string s = "Hello world!"; // source string
int index = 0; // index in the string where you want to make a replacement (starts at 0)
char c = '+'; // replacement symbol

// Checking index for correctness
if ((index >= 0) && (index < s.Length))
  s = s.Substring(0, index) + c.ToString() + s.Substring(index + 1);

Method 2. Using the loop operator.

// Method 2. Using the cycle and the additional string.
// If the index value is incorrect, then the original string does not change
// Input data:
string s = "Hello world!"; // source string
int index = 5; // replacement index (starts at 0)
char c = '+'; // replacement character

string s2 = ""; // additional string
for (int i = 0; i < s.Length; i++)
  if (i != index) s2 += s[i];
    else s2 += c;
  s = s2;

Method 3. Using the Remove() and Insert() methods. In this case, you also need to check the replacement index for correctness.

// Method 3. Methods Insert(), Remove()
// Input data:
string s = "Hello world!"; // the source string
int index = 5; // index in the string where you want to make a replacement (starts with 0)
char c = '+'; // replacement character

// Here you need to check for the pos value,
// if index is incorrect, an exception will be thrown
if ((index >= 0) && (index < s.Length))
  s = s.Remove(index, 1);
  s = s.Insert(index, c.ToString());