dir.by  
  Поиск  
Программирование, разработка, тестирование
C# (язык программирования)
Текст в C# (тип string и класс String)
Что такое текст В C# ? Тип string и класс String. Методы для работы с текстом.
  Посмотрели 11833 раз(а)    
 Что такое текст В C# ? Тип string и класс String. Методы для работы с текстом. 
последнее обновление: 27 ноября 2018
Для работы с текстом В C# используется тип string
  C#     Пример
string myText = "Hello";
Методы работы с текстом находятся в классе String.
Тип string является псевдонимом класса String.
То есть когда мы пишем:
string myText = "Hello";
мы можем использовать методы и переменные класса String.

Например, получить длину строки
int len = myText.Length;

или вызвать метод
book isSame = myText.CompareTo("House");

Текст В C# это последовательность символов Unicode.
Максимальный размер объекта String может составлять в памяти 2 ГБ, или около 1 миллиарда символов.
Свойства класса String
Length
Длина строки (количество символов)
  C#     Пример
string str1 = "Hello";
int v1 = str1.Length;
// v1 = 5
Методы класса String
CompareTo
Сравнивает текст с учетом регистра
подробнее: CompareTo ...
  C#     Пример
string str1 = "Hello";
string str2 = "Hello";
bool bIsSame = str1.CompareTo(str2)==0;
// bIsSame = true
ToLower
Конвертирует текст в нижний регистр (в маленькие буквы)
подробнее: ToLower...
  C#     Пример
string str1 = "HELLO World!";
string str2 = str1.ToLower();
// str1 = "HELLO World!"
// str2 = "hello world!"
ToUpper
Конвертирует текст в верхний регистр (в большие буквы)
подробнее: ToUpper...
  C#     Пример
string str1 = "Hello World!";
string str2 = str1.ToUpper();
// str1 = "Hello World!"
// str2 = "HELLO WORLD!"
Split
Разбивает текст на слова используя разделитель
подробнее: Split...
  C#     Пример
string text = "Hello! How do you do?"

string[] words = text.Split(' '); 
// массив words: 
// words[0] = "Hello!" 
// words[1] = "How" 
// words[2] = "do" 
// words[3] = "you" 
// words[4] = "do?"
StartsWith
Проверяет начало текста с указанным текстом (с учетом регистра)
подробнее: StartsWith ...
  C#     Пример 1
string str1 = "Hello world!";
string str2 = "He";
bool bStart = str1.StartsWith(str2);
// bStart = true


  C#     Пример 2
string str1 = "Hello world!";
string str2 = "HE";

// не учитываем регистр
bool bStart = str1.StartsWith(str2, StringComparison.OrdinalIgnoreCase);
// bStart = true
Contains
Проверяет содержит текст указанный текст или нет (с учетом регистра)
подробнее: Contains ...
  C#     Пример
string str1 = "Hello world!";
string str2 = "ello";
bool bFound = str1.Contains(str2);
// bFound = true
IndexOf
Ищет текст с учетом регистра и возвращает позицию
подробнее: IndexOf ...
  C#     Пример
string str1 = "Hello world!";
string str2 = "lo";
int pos = str1.IndexOf(str2);
// pos = 3
Substring
возвращает часть текста с указанной позиции и длиной
подробнее: Substring ...
  C#     Пример
string str1 = "Hello World!";
string str2 = str1.Substring(2, 5);
// str2 = "llo W"
IsNullOrEmpty
проверяет текст на пустой или на null
подробнее: IsNullOrEmpty ...
  C#     Пример
string name = "";
bool bIsEmpty = String.IsNullOrEmpty(name);
// bIsEmpty = true

IsNullOrWhiteSpace
проверяет текст на null или на пробелы
подробнее: IsNullOrWhiteSpace ...
  C#     Пример
string name = "   ";
bool bIsEmpty = String.IsNullOrWhiteSpace(name);
// bIsEmpty = true
[]
возвращает символ с указанной позиции
подробнее: [] ...
  C#     Пример
string str = "Hello World!";
char symbol = str[1];
// symbol = 'e'
String.Format
форматирование строки (заменяет текст на объекты)
подробнее: Format ...
  C#     Пример
string name = "Petr";
int year = 45;
string str = String.Format("Hello {0}, {1}", name, year);
// str = "Hello Petr, 45"
+
добавление текста
подробнее: + ...
  C#     Пример
string str1 = "Hello";
string str2 = "word";
string str = str1 + str2 + " people!";
// str = "Hello word people!"
$
интерполяция строк
подробнее: $ ...
  C#     Пример
int a = 5;
int b = 7;
string result = $"{a} + {b} = {a + b}";
// str = "5 + 7 = 12"
На заметку!
Несмотря на то, что тип string является ссылочным типом , операторы равенства (== и !=) определены для сравнения значений, а не ссылок.
Это упрощает проверку строк на равенство.
  C#     Создадим новое консольное приложение на C#... и напишем код
using System;

namespace ConsoleApplication1
{
     class Program
     {
          static void Main(string[] args)
          {
               // текст
               string str1 = "aaa";
               string str2 = "aaa";

               // равны ?
               bool isEqual = str1 == str2;
               // isEqual = true
          }
     }
}
Класс String (все методы и свойства)
String это класс, который представляет текст как последовательность символов Unicode.

namespace System

Версия .NETFramework\v4.6.1\mscorlib.dll

Синтаксис
public sealed class String : IComparable, ICloneable, IConvertible, IEnumerable, IComparable<string>, IEnumerable<char>, IEquatable<string>
Конструкторы
public String(char* value);
Initializes a new instance of the System.String class to the value indicated by a specified pointer to an array of Unicode characters. Читать далее ...
public String(char[] value);
Initializes a new instance of the System.String class to the value indicated by an array of Unicode characters. Читать далее ...
public String(sbyte* value);
Initializes a new instance of the System.String class to the value indicated by a pointer to an array of 8-bit signed integers. Читать далее ...
public String(char c, int count);
Initializes a new instance of the System.String class to the value indicated by a specified Unicode character repeated a specified number of times. Читать далее ...
public String(char* value, int startIndex, int length);
Initializes a new instance of the System.String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length. Читать далее ...
public String(char[] value, int startIndex, int length);
Initializes a new instance of the System.String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length. Читать далее ...
public String(sbyte* value, int startIndex, int length);
Initializes a new instance of the System.String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, and a length. Читать далее ...
public String(sbyte* value, int startIndex, int length, Encoding enc);
Initializes a new instance of the System.String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an System.Text.Encoding object. Читать далее ...

Свойства
public static readonly string Empty;
Represents the empty string. This field is read-only.
public int Length { get; }
Gets the number of characters in the current System.String object. Читать далее ...
public char this[int index] { get; }
Gets the System.Char object at a specified position in the current System.String object. Читать далее ...

Методика
public static bool operator !=(string a, string b);
Determines whether two specified strings have different values. Читать далее ...
public static bool operator ==(string a, string b);
Determines whether two specified strings have the same value. Читать далее ...
public object Clone();
Returns a reference to this instance of System.String. Читать далее ...
public static int Compare(string strA, string strB);
Compares two specified System.String objects and returns an integer that indicates their relative position in the sort order. Читать далее ...
public static int Compare(string strA, string strB, bool ignoreCase);
Compares two specified System.String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order. Читать далее ...
public static int Compare(string strA, string strB, StringComparison comparisonType);
Compares two specified System.String objects using the specified rules, and returns an integer that indicates their relative position in the sort order. Читать далее ...
public static int Compare(string strA, string strB, bool ignoreCase, CultureInfo culture);
Compares two specified System.String objects, ignoring or honoring their case, and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order. Читать далее ...
public static int Compare(string strA, string strB, CultureInfo culture, CompareOptions options);
Compares two specified System.String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two strings to each other in the sort order. Читать далее ...
public static int Compare(string strA, int indexA, string strB, int indexB, int length);
Compares substrings of two specified System.String objects and returns an integer that indicates their relative position in the sort order. Читать далее ...
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase);
Compares substrings of two specified System.String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order. Читать далее ...
public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType);
Compares substrings of two specified System.String objects using the specified rules, and returns an integer that indicates their relative position in the sort order. Читать далее ...
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, CultureInfo culture);
Compares substrings of two specified System.String objects, ignoring or honoring their case and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order. Читать далее ...
public static int Compare(string strA, int indexA, string strB, int indexB, int length, CultureInfo culture, CompareOptions options);
Compares substrings of two specified System.String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two substrings to each other in the sort order. Читать далее ...
public static int CompareOrdinal(string strA, string strB);
Compares two specified System.String objects by evaluating the numeric values of the corresponding System.Char objects in each string. Читать далее ...
public static int CompareOrdinal(string strA, int indexA, string strB, int indexB, int length);
Compares substrings of two specified System.String objects by evaluating the numeric values of the corresponding System.Char objects in each substring. Читать далее ...
public int CompareTo(object value);
Compares this instance with a specified System.Object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified System.Object. Читать далее ...
public int CompareTo(string strB);
Compares this instance with a specified System.String object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified string. Читать далее ...
public static string Concat(IEnumerable<string> values);
Concatenates the members of a constructed System.Collections.Generic.IEnumerable<T> collection of type System.String. Читать далее ...
public static string Concat<T>(IEnumerable<T> values);
Concatenates the members of an System.Collections.Generic.IEnumerable<T> implementation. Читать далее ...
public static string Concat(object arg0);
Creates the string representation of a specified object. Читать далее ...
public static string Concat(params object[] args);
Concatenates the string representations of the elements in a specified System.Object array. Читать далее ...
public static string Concat(params string[] values);
Concatenates the elements of a specified System.String array. Читать далее ...
public static string Concat(object arg0, object arg1);
Concatenates the string representations of two specified objects. Читать далее ...
public static string Concat(string str0, string str1);
Concatenates two specified instances of System.String. Читать далее ...
public static string Concat(object arg0, object arg1, object arg2);
Concatenates the string representations of three specified objects. Читать далее ...
public static string Concat(string str0, string str1, string str2);
Concatenates three specified instances of System.String. Читать далее ...
public static string Concat(object arg0, object arg1, object arg2, object arg3);
Concatenates the string representations of four specified objects and any objects specified in an optional variable length parameter list. Читать далее ...
public static string Concat(string str0, string str1, string str2, string str3);
Concatenates four specified instances of System.String. Читать далее ...
public bool Contains(string value);
Returns a value indicating whether a specified substring occurs within this string. Читать далее ...
public static string Copy(string str);
Creates a new instance of System.String with the same value as a specified System.String. Читать далее ...
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
Copies a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters. Читать далее ...
public bool EndsWith(string value);
Determines whether the end of this string instance matches the specified string. Читать далее ...
public bool EndsWith(string value, StringComparison comparisonType);
Determines whether the end of this string instance matches the specified string when compared using the specified comparison option. Читать далее ...
public bool EndsWith(string value, bool ignoreCase, CultureInfo culture);
Determines whether the end of this string instance matches the specified string when compared using the specified culture. Читать далее ...
public override bool Equals(object obj);
Determines whether this instance and a specified object, which must also be a System.String object, have the same value. Читать далее ...
public bool Equals(string value);
Determines whether this instance and another specified System.String object have the same value. Читать далее ...
public static bool Equals(string a, string b);
Determines whether two specified System.String objects have the same value. Читать далее ...
public bool Equals(string value, StringComparison comparisonType);
Determines whether this string and a specified System.String object have the same value. A parameter specifies the culture, case, and sort rules used in the comparison. Читать далее ...
public static bool Equals(string a, string b, StringComparison comparisonType);
Determines whether two specified System.String objects have the same value. A parameter specifies the culture, case, and sort rules used in the comparison. Читать далее ...
public static string Format(string format, object arg0);
Replaces one or more format items in a specified string with the string representation of a specified object. Читать далее ...
public static string Format(string format, params object[] args);
Replaces the format item in a specified string with the string representation of a corresponding object in a specified array. Читать далее ...
public static string Format(IFormatProvider provider, string format, object arg0);
Replaces the format item or items in a specified string with the string representation of the corresponding object. A parameter supplies culture-specific formatting information. Читать далее ...
public static string Format(IFormatProvider provider, string format, params object[] args);
Replaces the format items in a specified string with the string representations of corresponding objects in a specified array. A parameter supplies culture-specific formatting information. Читать далее ...
public static string Format(string format, object arg0, object arg1);
Replaces the format items in a specified string with the string representation of two specified objects. Читать далее ...
public static string Format(IFormatProvider provider, string format, object arg0, object arg1);
Replaces the format items in a specified string with the string representation of two specified objects. A parameter supplies culture-specific formatting information. Читать далее ...
public static string Format(string format, object arg0, object arg1, object arg2);
Replaces the format items in a specified string with the string representation of three specified objects. Читать далее ...
public static string Format(IFormatProvider provider, string format, object arg0, object arg1, object arg2);
Replaces the format items in a specified string with the string representation of three specified objects. An parameter supplies culture-specific formatting information. Читать далее ...
public CharEnumerator GetEnumerator();
Retrieves an object that can iterate through the individual characters in this string. Читать далее ...
public override int GetHashCode();
Returns the hash code for this string. Читать далее ...
public TypeCode GetTypeCode();
Returns the System.TypeCode for class System.String. Читать далее ...
public int IndexOf(char value);
Reports the zero-based index of the first occurrence of the specified Unicode character in this string. Читать далее ...
public int IndexOf(string value);
Reports the zero-based index of the first occurrence of the specified string in this instance. Читать далее ...
public int IndexOf(char value, int startIndex);
Reports the zero-based index of the first occurrence of the specified Unicode character in this string. The search starts at a specified character position. Читать далее ...
public int IndexOf(string value, int startIndex);
Reports the zero-based index of the first occurrence of the specified string in this instance. The search starts at a specified character position. Читать далее ...
public int IndexOf(string value, StringComparison comparisonType);
Reports the zero-based index of the first occurrence of the specified string in the current System.String object. A parameter specifies the type of search to use for the specified string. Читать далее ...
public int IndexOf(char value, int startIndex, int count);
Reports the zero-based index of the first occurrence of the specified character in this instance. The search starts at a specified character position and examines a specified number of character positions. Читать далее ...
public int IndexOf(string value, int startIndex, int count);
Reports the zero-based index of the first occurrence of the specified string in this instance. The search starts at a specified character position and examines a specified number of character positions. Читать далее ...
public int IndexOf(string value, int startIndex, StringComparison comparisonType);
Reports the zero-based index of the first occurrence of the specified string in the current System.String object. Parameters specify the starting search position in the current string and the type of search to use for the specified string. Читать далее ...
public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType);
Reports the zero-based index of the first occurrence of the specified string in the current System.String object. Parameters specify the starting search position in the current string, the number of characters in the current string to search, and the type of search to use for the specified string. Читать далее ...
public int IndexOfAny(char[] anyOf);
Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. Читать далее ...
public int IndexOfAny(char[] anyOf, int startIndex);
Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. The search starts at a specified character position. Читать далее ...
public int IndexOfAny(char[] anyOf, int startIndex, int count);
Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. The search starts at a specified character position and examines a specified number of character positions. Читать далее ...
public string Insert(int startIndex, string value);
Returns a new string in which a specified string is inserted at a specified index position in this instance. Читать далее ...
public static string Intern(string str);
Retrieves the system's reference to the specified System.String. Читать далее ...
public static string IsInterned(string str);
Retrieves a reference to a specified System.String. Читать далее ...
public bool IsNormalized();
Indicates whether this string is in Unicode normalization form C. Читать далее ...
public bool IsNormalized(NormalizationForm normalizationForm);
Indicates whether this string is in the specified Unicode normalization form. Читать далее ...
public static bool IsNullOrEmpty(string value);
Indicates whether the specified string is null or an System.String.Empty string. Читать далее ...
public static bool IsNullOrWhiteSpace(string value);
Indicates whether a specified string is null, empty, or consists only of white-space characters. Читать далее ...
public static string Join(string separator, IEnumerable<string> values);
Concatenates the members of a constructed System.Collections.Generic.IEnumerable<T> collection of type System.String, using the specified separator between each member. Читать далее ...
public static string Join<T>(string separator, IEnumerable<T> values);
Concatenates the members of a collection, using the specified separator between each member. Читать далее ...
public static string Join(string separator, params object[] values);
Concatenates the elements of an object array, using the specified separator between each element. Читать далее ...
public static string Join(string separator, params string[] value);
Concatenates all the elements of a string array, using the specified separator between each element. Читать далее ...
public static string Join(string separator, string[] value, int startIndex, int count);
Concatenates the specified elements of a string array, using the specified separator between each element. Читать далее ...
public int LastIndexOf(char value);
Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance. Читать далее ...
public int LastIndexOf(string value);
Reports the zero-based index position of the last occurrence of a specified string within this instance. Читать далее ...
public int LastIndexOf(char value, int startIndex);
Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string. Читать далее ...
public int LastIndexOf(string value, int startIndex);
Reports the zero-based index position of the last occurrence of a specified string within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string. Читать далее ...
public int LastIndexOf(string value, StringComparison comparisonType);
Reports the zero-based index of the last occurrence of a specified string within the current System.String object. A parameter specifies the type of search to use for the specified string. Читать далее ...
public int LastIndexOf(char value, int startIndex, int count);
Reports the zero-based index position of the last occurrence of the specified Unicode character in a substring within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions. Читать далее ...
public int LastIndexOf(string value, int startIndex, int count);
Reports the zero-based index position of the last occurrence of a specified string within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions. Читать далее ...
public int LastIndexOf(string value, int startIndex, StringComparison comparisonType);
Reports the zero-based index of the last occurrence of a specified string within the current System.String object. The search starts at a specified character position and proceeds backward toward the beginning of the string. A parameter specifies the type of comparison to perform when searching for the specified string. Читать далее ...
public int LastIndexOf(string value, int startIndex, int count, StringComparison comparisonType);
Reports the zero-based index position of the last occurrence of a specified string within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string for the specified number of character positions. A parameter specifies the type of comparison to perform when searching for the specified string. Читать далее ...
public int LastIndexOfAny(char[] anyOf);
Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. Читать далее ...
public int LastIndexOfAny(char[] anyOf, int startIndex);
Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. The search starts at a specified character position and proceeds backward toward the beginning of the string. Читать далее ...
public int LastIndexOfAny(char[] anyOf, int startIndex, int count);
Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions. Читать далее ...
public string Normalize();
Returns a new string whose textual value is the same as this string, but whose binary representation is in Unicode normalization form C. Читать далее ...
public string Normalize(NormalizationForm normalizationForm);
Returns a new string whose textual value is the same as this string, but whose binary representation is in the specified Unicode normalization form. Читать далее ...
public string PadLeft(int totalWidth);
Returns a new string that right-aligns the characters in this instance by padding them with spaces on the left, for a specified total length. Читать далее ...
public string PadLeft(int totalWidth, char paddingChar);
Returns a new string that right-aligns the characters in this instance by padding them on the left with a specified Unicode character, for a specified total length. Читать далее ...
public string PadRight(int totalWidth);
Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length. Читать далее ...
public string PadRight(int totalWidth, char paddingChar);
Returns a new string that left-aligns the characters in this string by padding them on the right with a specified Unicode character, for a specified total length. Читать далее ...
public string Remove(int startIndex);
Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted. Читать далее ...
public string Remove(int startIndex, int count);
Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted. Читать далее ...
public string Replace(char oldChar, char newChar);
Returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character. Читать далее ...
public string Replace(string oldValue, string newValue);
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string. Читать далее ...
public string[] Split(params char[] separator);
Splits a string into substrings that are based on the characters in an array. Читать далее ...
public string[] Split(char[] separator, int count);
Splits a string into a maximum number of substrings based on the characters in an array. You also specify the maximum number of substrings to return. Читать далее ...
public string[] Split(char[] separator, StringSplitOptions options);
Splits a string into substrings based on the characters in an array. You can specify whether the substrings include empty array elements. Читать далее ...
public string[] Split(string[] separator, StringSplitOptions options);
Splits a string into substrings based on the strings in an array. You can specify whether the substrings include empty array elements. Читать далее ...
public string[] Split(char[] separator, int count, StringSplitOptions options);
Splits a string into a maximum number of substrings based on the characters in an array. Читать далее ...
public string[] Split(string[] separator, int count, StringSplitOptions options);
Splits a string into a maximum number of substrings based on the strings in an array. You can specify whether the substrings include empty array elements. Читать далее ...
public bool StartsWith(string value);
Determines whether the beginning of this string instance matches the specified string. Читать далее ...
public bool StartsWith(string value, StringComparison comparisonType);
Determines whether the beginning of this string instance matches the specified string when compared using the specified comparison option. Читать далее ...
public bool StartsWith(string value, bool ignoreCase, CultureInfo culture);
Determines whether the beginning of this string instance matches the specified string when compared using the specified culture. Читать далее ...
public string Substring(int startIndex);
Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string. Читать далее ...
public string Substring(int startIndex, int length);
Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length. Читать далее ...
public char[] ToCharArray();
Copies the characters in this instance to a Unicode character array. Читать далее ...
public char[] ToCharArray(int startIndex, int length);
Copies the characters in a specified substring in this instance to a Unicode character array. Читать далее ...
public string ToLower();
Returns a copy of this string converted to lowercase. Читать далее ...
public string ToLower(CultureInfo culture);
Returns a copy of this string converted to lowercase, using the casing rules of the specified culture. Читать далее ...
public string ToLowerInvariant();
Returns a copy of this System.String object converted to lowercase using the casing rules of the invariant culture. Читать далее ...
public override string ToString();
Returns this instance of System.String; no actual conversion is performed. Читать далее ...
public string ToString(IFormatProvider provider);
Returns this instance of System.String; no actual conversion is performed. Читать далее ...
public string ToUpper();
Returns a copy of this string converted to uppercase. Читать далее ...
public string ToUpper(CultureInfo culture);
Returns a copy of this string converted to uppercase, using the casing rules of the specified culture. Читать далее ...
public string ToUpperInvariant();
Returns a copy of this System.String object converted to uppercase using the casing rules of the invariant culture. Читать далее ...
public string Trim();
Removes all leading and trailing white-space characters from the current System.String object. Читать далее ...
public string Trim(params char[] trimChars);
Removes all leading and trailing occurrences of a set of characters specified in an array from the current System.String object. Читать далее ...
public string TrimEnd(params char[] trimChars);
Removes all trailing occurrences of a set of characters specified in an array from the current System.String object. Читать далее ...
public string TrimStart(params char[] trimChars);
Removes all leading occurrences of a set of characters specified in an array from the current System.String object. Читать далее ...
 
← Предыдущая тема
Алгоритм пересечения прямоугольников
 
Следующая тема →
Length (длина строки в C#). Пример: string str1 = "Hello"; int v1 = str1.Length;
 
Ваши Отзывы ... комментарии ...
   
Вашe имя
Ваш комментарий (www ссылки может добавлять только залогиненный пользователь)

  Объявления  
  Объявления  
 
Загрузка и установка Microsoft Visual Studio
Скачать и установить Visual Studio 2022 (для изучения C#, написание программ: WPF, ASP.NET, ASP.NET Core, UWP, Miaui, Xamarin, Unity, MonoGame)
Скачать и установить Visual Studio 2019 (для изучения C#, написание программ: WPF, ASP.NET, ASP.NET Core, Xamarin, Unity, MonoGame)
Загрузка и установка Visual Studio 2017 (для изучения C#, написание программ: WPF, ASP.NET, ASP.NET Core, Xamarin, Unity, MonoGame)
Новое приложение для изучения C#
Создаем новое консольное приложение для изучения C#
Отладка кода
Debug.Assert(false) Отладка кода в C#
Для отладки, опция "Common Language Runtime Exceptions" увидеть исключения, когда выполняется программа C#
Атрибут [Obsolete("Мой метод устарел. Не используйте", false)] Предупреждение при компиляции кода в C#
Типы данных C#
C# типы данных: число (bool, char, byte, int, long, float, double, decimal), текст (string), перечисление (enum), класс (class), структура (struct)
Структура Boolean В C# это флаг со значениями true или false (bool) и методы для конвертации bool
Структура Int32 В C# это целое число со знаком (int) и методы для конвертации int
Структура Single В C# это число с плавающей запятой (float) и методы для конвертации float
var ... Переменная любого типа В C#. Пример: var str = "Hello!";
Тип dynamic В C#
Значения по умолчанию В C#
Хранение объектов в памяти. Удаление объектов из памяти
Ссылочные типы и типы значений В C#
Стэк (stack) - память для параметров метода и локальных переменных В C#
Heap - динамическая память доступная во время выполнения программы В C#
Интерфейс IDisposable. Пишем код для правильного освобождения неуправляемых ресурсов в деструкторе и в интерфейсе IDisposable В C#
Память. Сборщик мусора (garbage collector). Автоматическое освобождение памяти В C#
C# конвертация типов
C# конвертация строки в число (string → short, int, long, ushort, uint, ulong, float, double, decimal) | используем Culture (настройки системы)
C# конвертация числа в строку (int, double, short, ... → string) с требуемой точностью
Текст в C# (тип string и класс String)
Алгоритм пересечения прямоугольников
Что такое текст В C# ? Тип string и класс String. Методы для работы с текстом.
Length (длина строки в C#). Пример: string str1 = "Hello"; int v1 = str1.Length;
CompareTo (сравнивает текст с учетом регистра в C#). Пример: bool bIsSame = str1.CompareTo(str2)==0;
ToLower (конвертирует текст в нижний регистр в C#). Пример: string str1 = "HELLO World!"; string str2 = str1.ToLower();
ToUpper (конвертирует текст в верхний регистр в C#). Пример: string str1 = "Hello World!"; string str2 = str1.ToUpper();
Split (разбить строку на слова в C#). Пример: string[] arrWords = strText.Split(' ');
StartsWith (проверяет начало текста с указанным текстом с учетом регистра в C#). Пример: bool bStart = str1.StartsWith(str2);
Contains (проверяет содержит текст указанный текст или нет с учетом регистра в C#). Пример: bool bFound = str1.Contains(str2);
IndexOf (ищет строку с учетом регистра и возвращает позицию в C#). Пример: int pos = str1.IndexOf(str2);
Substring (возвращает часть текста с указанной позиции и длиной В C#). Пример: string str1 = "Hello World!"; string str2 = str1.Substring(2, 5);
IsNullOrEmpty (проверяет текст на пустой или на null В C#). Пример: string name = "Hello World!"; bool bFlag = String.IsNullOrEmpty(name);
IsNullOrWhiteSpace (проверяет текст на null или на текст с пробелами В C#). Пример: string name = "   "; bool bFlag = String.IsNullOrWhiteSpace(name);
[] (возвращает символ с указанной позиции В C#). Пример: char symbol = str[1];
Format (форматирование текста, строки В C#). Пример: string strNew = String.Format("Hello {0}, {1}", name, year);
+ (добавление строк и текста В C#). Пример: string str = str1 + str2 + " people!";
$ (интерполяция строк В C#). Пример: string result = $"Hello {a} + {b} = {a + b}";
Символ @ перед началом строки В C#. Пример: string str1 = @"aaa";
Используем вместе @ и $ (интерполяцию строк в C#)
DateTime (дата и время) в C#
Что такое DateTime в C# ? Конвертация в строку с форматом
Перечисления в C# (enum)
Что такое перечисление (enum) В C# ?
Как преобразовать текст в enum в C#
Как перечислить все элементы в enum в C#
null
null значение для простых типов. Используем ? или Nullable В C#
Оператор ?? (null-объединение) В C#
try-catch
Обработка исключений в C#. Оператор try catch finally
Классы в C# (class)
Что такое класс В C#?
Модификаторы доступа класса В C#. Модификаторы доступа для методов, свойств, полей В C#
'partial class' В C#. Описание класса в разных файлах
Конструкторы для класса
Конструктор класса В C#
Инициализация объекта класса (установка значений для полей) В C#
Вызов конструктора у базового класса В C#
Статический конструктор в классе C#
'base' Для вызова метода из базового класса. Для вызова переменной из базового класса. Для вызова конструктора из базового класса. C#
'this' Для установки или получения значения у поля класса. Для вызова конструктора из класса. C#
Деструкторы для класса
Деструктор класса В C#
Деструкторы в классах (как вызываются базовые деструкторы) C#
Наследование
Что такое наследование класса в C# ?
Наследование с использованием new
Используем new для метода интерфейса. Наследование интерфейса от интерфейса с одинаковым методом
Используем new для метода класса. Наследование класса от класса в C#.
Наследование с использованием sealed
sealed class. Запрет наследоваться В C#
Наследование класса от класса в C#. Используем слова virtual, override, sealed для методов класса
Абстрактный класс
Что такое абстрактный класс В C# ? Абстрактные методы, свойства, индексы.
Наследование от класса abstract В C#. Используем abstract и override для методов класса
Константы и readonly поля в классе
Константы в классе C#
readonly . Для поля класса. Это поле только для чтения в C#
Свойства get и set в классе C# (аксессоры)
get set Свойства в классе C#
Наследование (virtual, override) для аксессоров get и set в C#
Операторы, индексаторы в C#
Операторы в классе C#. Перегрузка операторов: > < ++ + true false
Индексаторы в классе C#
Вложенные типы в C#
Вложенный класс, структура в C#
Параметры в методе класса C#
ref и out (возврат параметров по ссылке в методе) C#. Пример: public void AddValue(ref int value)
Параметры по умолчанию (необязательные параметры) в методе C#. Пример: public int CalculateSum(int a, int b, int c=7)
Именованные параметры C#. Пример: public void CalculateSum(a:7, b:3);
Универсальные методы, универсальные классы в C# (шаблоны)
Метод с универсальными параметрами в C# (шаблоны). Пример: public double Sum<T1, T2>(T1 value1, T2 value2) { ... }
Обобщенный (типизированный) класс в C# (шаблоны). Пример class Book<T> { ... }
where Ограничение типа в обобщенном (типизированном) классе в C# (шаблоны). Пример class Dog<T> where T : Cat
Преобразование объекта класса из одного типа в другой
explicit это явный оператор преобразования в классе C#
implicit это неявный оператор преобразования в классе C#
Преобразование объекта класса из одного типа в другой в C#. Используем try ( ) is as
Преобразование объекта класса из одного типа в другой в C#. Используем pattern matching is switch
Объект класса в C#
? оператор условного null в C#
Объект класса содержит ссылку в C#
Как чтобы при копировании объектов в C# копировались данные класса, а не ссылка?
Статический конструктор и статические свойства и методы
Статический конструктор в классе C#
Статические методы, свойства, члены в классе C#
Дополнительные возможности класса в C#
Метод расширения в C# (this в первом параметре метода). Пример: static public void AddValues(this List<int> myList, int value1, int value2)
Правила именования классов в C#
Какими буквами строчными или заглавными называть классы, методы, свойства ... в C#
Правильно ли для каждого класса в C# создавать свой .cs файл? Или писать классы C# в одном .cs файле?
Статический класс
Статический класс в C#
Анонимный класс
Объект с анонимным (отсутствующим) типом в C#. Пример: var book = new { BookName = "Властелин Колец", Price = 100 };
Интерфейсы
Что такое interface в C# ?
Наследование interface от interface в C#
Наследование класса от класса от interface в C#. Используем override и virtual для методов класса
Обобщенный (типизированный) интерфейс в C# (шаблоны). Пример interface IUser<T> { ... }
Структура struct
Что такое структура в C#?
Модификаторы доступа структуры в C#. Модификаторы доступа для методов, свойств, полей структуры в C#
Инициализация объекта структуры (установка значений для полей) в C#
Как поменять значение в массиве структур или в коллекции структур (List) в C#
Вложенная структура в C#
Преобразование объекта структуры из одного типа в другой
implicit это неявный оператор преобразования структуры в C#
explicit это явный оператор преобразования структуры в C#
Отложенная загрузка class Lazy в C#
Отложенное создание объекта в памяти (class Lazy в C#)
Кортежи (tuple)
Кортежи (tuple) в C#
Динамические объекты с любыми свойствами
DynamicObject и ExpandoObject в C#
Массивы
Что такое массивы? array в C#
Инициализация массива (заполнение элементов массива array) в C#
params передача любого количества параметров в метод в C#
Класс Array (для работы с массивом) C#
Коллекции
Что такое коллекции в C# ?
Что такое необобщенные коллекции в C# ? Классы ArrayList, Stack, Queue, Hashtable, SortedList, BitArray
Что такое обобщенные (типизированные) коллекции в C# ? Классы List<T>, SortedList<T>, Stack<T>, Dictionary<TKey,TValue>, LinkedList<T>, Queue<T>, HashSet<T>, SortedSet<T>, ConcurrentDictionary<TKey, TValue>, SortedDictionary<TKey, TValue>
Классы необобщенных коллекций (в одной коллекции хранятся элементы разного типа)
Интерфейс IEnumerable. Самый базовый интерфейс для коллекций в C#
Интерфейсы: ICollection, IList, IDictionary. Основа для коллекций в C#
Класс ArrayList (коллекция в C#)
Что такое ArrayList в C# ?
Класс SortedList (коллекция в C#)
Что такое SortedList в C# ?
Класс Stack (коллекция в C#)
Что такое Stack в C# ?
Класс Queue (коллекция в C#)
Что такое Queue в C# ?
Класс Hashtable (коллекция в C#)
Что такое Hashtable в C# ?
Класс BitArray (коллекция в C#)
Что такое BitArray в C# ?
Классы обобщенных, типизированных коллекций в C# (в одной коллекции хранятся элементы одного типа)
Интерфейс IEnumerable<T>. Самый базовый интерфейс для типизированных коллекций в C#
Интерфейсы: ICollection<T>, IList<T>, ISet<T>, IDictionary<TKey, TValue>. Основа для типизированных коллекций в C#
Класс List<T> (типизированная коллекция в C#)
Что такое List<T> в C# ?
Инициализация коллекции List в фигурных скобках В C#
for, foreach (проходим все элементы в List<T>) в C#
Find (ищем элемент по критерию в List<T>) в C#
FindAll (ищем список элементов по критерию в List<T>) в C#
ForEach (для каждого элемента List<T> выполняется действие) в C#
Класс LinkedList<T> (типизированная коллекция в C#)
Что такое LinkedList<T> в C# ?
Класс SortedList<TKey, TValue> (типизированная коллекция в C#)
Что такое SortedList<TKey, TValue> в C# ?
Класс Stack<T> (типизированная коллекция в C#)
Что такое Stack<T> в C# ?
Класс Queue<T> (типизированная коллекция в C#)
Что такое Queue<T> в C# ?
Класс HashSet<T> (типизированная коллекция в C#)
Что такое HashSet<T> в C# ?
Как устроен HashSet<T> в C#
Класс SortedSet<T> (типизированная коллекция в C#)
Что такое SortedSet<T> в C# ?
Класс ObservableCollection<T> (типизированная коллекция в C#)
Что такое ObservableCollection<T> в C# ?
Класс Dictionary<TKey, TValue> (типизированная коллекция в C#)
Что такое Dictionary<TKey, TValue> в C# ?
Инициализация элементов в конструкторе Dictionary<TKey, TValue> в C#
Как устроен Dictionary<TKey, TValue> в C#
Как в C# сконвертировать IEnumerable в → Dictionary<TKey, TValue> . Используем метод ToDictionary
Класс SortedDictionary<TKey, TValue> (типизированная коллекция в C#)
Что такое SortedDictionary<TKey, TValue> в C# ?
Класс ConcurrentDictionary<TKey, TValue> (типизированная коллекция в C#)
Что такое ConcurrentDictionary<TKey, TValue> в C# ?
AddOrUpdate (добавить или обновить значение по ключу в ConcurrentDictionary<TKey, TValue>) в C#
Асимптотическая сложность для добавления, удаления, взятия элемента в коллекциях
Асимптотическая сложность для добавления, удаления, взятия элемента в коллекциях C# (List, SortedList, Stack, Dictionary, LinkedList, Queue, HashSet, SortedSet, ConcurrentDictionary, SortedDictionary)
Сортировка элементов в массиве [] и коллекции List
Сортировка элементов в массиве [] и коллекции List<T> в C#. Интерфейс IComparable
Сортировка элементов в массиве [] и коллекции List<T> в C#. Интерфейс IComparer
Моя реализация IEnumerator, IEnumerable и итераторы
Пример: Моя реализация интерфейсов IEnumerable и IEnumerator в C#
Итераторы и yield в C#. Примеры реализации IEnumerable с помощью yield
Методы расширения для IEnumerable (поиск, замена, выборка значений) в C#
Методы поиска, замены, выборки значений в IEnumerable<T>. Методы расширений для IEnumerable<T> в C#
Any (метод расширения IEnumerable<T>) в C#
Select (метод расширения IEnumerable<T>) в C#
GroupBy (метод расширения IEnumerable<T>) В C#
GroupJoin (метод расширения IEnumerable<T>) В C#
Сортировка, фильтрация в LINQ (Language-Integrated Query)
Что такое LINQ в C# ?
Сортировка, фильтрация элементов списка с помощью LINQ в C#
Книги для изучения LINQ в C#
Указатели
Указатели в C#. Оператор unsafe
Указатели на структуры, поля классов, массивы в C# . Операторы unsafe, stackalloc, fixed
Работа с файлами
Открываем файл, читаем текст из файла и разбиваем по словам. C#
Создаем текстовый файл, пишем текст в файл C#
Создаем HTML файл, пишем табличные данные в HTML файл | C#
Создаем бинарный файл, пишем байты в файл C#
Частичная загрузка файла с FTP в C#
Класс Path. Метод Combine - объединяет строки в полный путь файла. И другие методы класса Path | C#
Сериализация
Что такое сериализация объекта в C# ? Атрибут [Serializable]
Сериализация C# объекта в бинарный файл. Класс BinaryFormatter. Атрибут [Serializable]
Сериализация C# объекта в XML файл. Класс XmlSerializer. Атрибут [Serializable]
Сериализация C# объекта в JSON файл. Класс DataContractJsonSerializer. Атрибут [Serializable]
Сериализация C# объекта в SOAP файл. Класс SoapFormatter. Атрибут [Serializable]
Пространства имен
Пространства имен namespace using в C#
Delegate
Делегат (delegate) в C#
Добавление метода(методов) в делегате C#. Объединение делегатов. Удаление метода из делегата
Делегат как параметр в методе C#
Безымянный, анонимный метод в C# (метод описанный на месте параметра, делегата)
Универсальные делегаты
Универсальные, обобщенные делегаты в C# (шаблоны)
Универсальные делегаты Action, Predicate и Func в C#
События
События (event) в C#
Лямда
Лямда (пример) в C#
Регулярные выражения
Регулярные выражения в C#
Разбиваем текст на слова (регулярные выражения в c#)
Ставим * вместо фамилии после первой буквы (регулярные выражения в c#)
Разбиваем текст на слова (регулярные выражения в c#)
Процесс, модули процесса
Процесс в C# (класс Process)
Модули процесса в С# (класс ProcessModule)
Потоки, многопоточность
Потоки в C# (класс Thread)
Пул потоков в C# (Thread Pool)
В чем отличие background (фоновый поток) и foreground (на переднем плане поток) в C# ?
Синхронизация потоков в C#
Parallel Library Task (TPL) Параллельное программирование задач
Parallel Library Task (TPL). Библиотека параллельных задач в C#
Класс Parallel используя метод Invoke параллельно выполненяет методы, циклов for и foreach (на разных ядрах процессора) в C#
PLINQ распараллеливает LINQ запросы для выполнения на разных ядрах процессора в C#
Асинхронные методы (async и await)
class Task в C#
Асинхронное программирование в C# (async, await как оформлять)
Асинхронное программирование в C# (используем async, await и Task на примере)
Асинхронное программирование в C# (теория)
Домены приложений
Что такое Домены приложений в C# ? (класс AppDomain)
Пример "Информация о домене приложения" (имя текущего домена, перечисляем сборки) в C#
Пример "Создаем 2-ой домен приложения. Пишем класс в 1-ом домене и используем во 2-ом домене. MarshalByRefObject в C#
Пример "Загружаем 2-ой домен приложения из файла, запускаем вычисления, выгружаем 2-ой домен из памяти" в C#
Атрибуты
Атрибуты для класса, метода, свойства в C#
Атрибут [Conditional("AAA")] . Для компиляции игнорировать метод или свойство если не определен символ условной компиляции в C#
Атрибут [Obsolete("Мой метод устарел. Не используйте", false)] Предупреждение при компиляции кода в C#
Атрибут [Display(Name = "Sleep at night")] . Для хранения какого нибудь текста прикрепленного к переменной | C#
Аттрибут [Required(ErrorMessage = "Пожалуйста, введите название")] описывается для свойства в C# классе и требует чтобы свойство было заполнено, если не заполнено на экране ошибка ErrorMessage в ASP.NET MVC
Аттрибут [Remote("IsValidAuthor", "Home", ErrorMessage = "Enter correct author of book")] описывается для свойства в C# классе и проверяет это свойство на правильность на сервере через метод IsValidAuthor в conroller Home, если метод возвращает false, то на экране будет ошибка ErrorMessage в ASP.NET MVC
Рефлексия (отражение) reflection в C#
Оператор nameof в C# (имя класса, имя метода, имя переменной)
Что такое рефлексия (отражение) в C# ? Класс Type
Создание объекта класса и вызов конструтора с параметрами используя рефлексию (отражение) reflection в C#
Как получить информацию атрибута для метода у класса. Используем reflection (отражение)
Как получить информацию атрибута для свойства у класса. Используем reflection (отражение)
Директивы препроцессора (if при компиляции)
Директивы препроцессора #define #undef #if #elif #else #endif в C#
Как определить #define для всех файлов (для всего проекта) в С# ?
Что такое сборка и исполняющая среда CLR ?
Сборка (Assembly) в C#. Компиляция. Промежуточный код IL (Intermediate Language). Метаданные.
Как подключить C# сборку в проект?
Утилита ildasm.exe. Конвертирует сборку (C# exe, dll файл) в промежуточный язык IL (Intermediate Language). Эта утилита удобна для изучения
Исполняющая среда CLR (Common Language Runtime) в C# . JIT (Just-In-Time) компилятор.
Создание и подключение нашей сборки
Создание нашей C# сборки (обычная сборка)
Подключение нашей C# сборки (обычная сборка)
Создание нашей C# сборки (разделяемая сборка)
Подключение нашей C# сборки (разделяемая сборка)
База данных в консольном приложении C#
Entity Framework в консольном приложении C#. Используем Code First (пишем c# код, а таблицы в базе данных создаются сами)
Читаем картинку из базы данных и сохраняем в файл | ADO.NET, C#, консольное приложение
Внедрение зависимостей (Dependency Injection) DI в C#
Dependency Injection (DI) Внедрение зависимостей в C#
Ninject (IoC-контейнер) управление зависимостями в C#
Autofac (IoC-контейнер) управление зависимостями в C#
Удобные утилиты Visual Studio
Графическая диаграмма классов в C# (View Class Diagram)
exe to C# code
"dotPeek" application for decompile (disassemble) exe to c# source code
В приложении C# вызываем C++ функции
Что такое управляемый код (managed code) и неуправляемый код (unmanaged code) ? | C# и C++
Маршалинг (marshalling) в C#. Преобразование типов между управляемым кодом (managed code) и неуправляемым кодом (unmanaged code)
В приложении C# вызываем функции из Windows dll (C++ WinAPI). Атрибут [DllImport("user32.dll")]
В приложении C# вызываем функции из моей dll (C++). Атрибут [DllImport("My.dll", CallingConvention = CallingConvention.Cdecl)]
Дополнительные темы, вопросы
Не создается новый проект в Visual Studio 2019. Ошибка "Object reference not set to instance of an object"
Ошибка компиляции C#: error CS1106: Extension method must be defined in a non-generic static class
Ошибка компиляции C#: error CS0246: The type or namespace name 'Point' could not be found (are you missing a using directive or an assembly reference?)
Почему метод Dictionary.TryGetValue не может найти значение по ключу в C# ?
Объектно-ориентированное программирование (ООП). Принципы ООП: абстрагирование, инкапсуляция, наследование, полиморфизм
Какими буквами в C# (заглавными или строчными или прописными) называть поля, методы в классе, интерфейсы, делегаты, параметры ?
Правильно ли для каждого класса в C# создавать свой .cs файл? Или писать классы C# в одном .cs файле?
Что лучше использовать встроенный тип int или класс Integer (тип string или класс String) на C#?
Как скачать и установить нужную .NET Framework версию в Visual Studio ?
Упаковка и распаковка значимых типов в C# (boxing/unboxing)
Error CS8107 Feature 'default literal' is not available in C# 7.0. Please use language version 7.1 or greater
Error "unable to connect to web server "iis express" | C# | Visual Studio 2017
Удаляем и устанавливаем NuGet в Visual Studio
При открытии проекта в Visual Studio 2019 ошибка: "project requires 'SQL Server 2012 Express LocalDB' which is not installed on this computer"
Математические операторы checked и unchecked
Математический оператор unchecked в C#
Математический оператор checked в C#
Дополнительный C# классы
C# класс Random
C# структура Point
C# структура PointF
C# структура Size
C# структура SizeF
C# структура Rectangle
C# структура RectangleF
Время
Время, истекшее с момента загрузки системы (в миллисекундах). System.Environment.TickCount в C#
Шифрование / Cryptography
Зашифруем пароль и проверим | C# console application
Excell
Чтение excel файла на C# (сonsole application)
WWW сайты для изучения C#
Сайты для изучения C#

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика