C — Strings
Strings are actually one-dimensional array of characters terminated by a null character ‘\0’. Thus a null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word «Hello». To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word «Hello.»
If you follow the rule of array initialization then you can write the above statement as follows −
Following is the memory presentation of the above defined string in C/C++ −
Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the ‘\0’ at the end of the string when it initializes the array. Let us try to print the above mentioned string −
When the above code is compiled and executed, it produces the following result −
C supports a wide range of functions that manipulate null-terminated strings −
strcpy(s1, s2);
Copies string s2 into string s1.
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
Returns the length of string s1.
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
The following example uses some of the above-mentioned functions −
When the above code is compiled and executed, it produces the following result −
Text c что это
Answered by:
Question
I just now started C#/. Can any one say what it means by "System.Text"
Answers
System.Text is a namespace. In .Net, classes all have a so called namespace and you can use the classes by either fully qualify them (e.g. System.Text.Encoder) or place a using statement on top (e.g. using System.Text; will enable you to just use Encoder).
With kind regards,
- Marked as answer by raamee Sunday, February 6, 2011 12:00 PM
All replies
System.Text is a namespace. In .Net, classes all have a so called namespace and you can use the classes by either fully qualify them (e.g. System.Text.Encoder) or place a using statement on top (e.g. using System.Text; will enable you to just use Encoder).
With kind regards,
- Marked as answer by raamee Sunday, February 6, 2011 12:00 PM
Dev centers
- Windows
- Office
- Visual Studio
- Microsoft Azure
- More.
Learning resources
- Microsoft Virtual Academy
- Channel 9
- MSDN Magazine
Community
- Forums
- Blogs
- Codeplex
Support
Programs
- BizSpark (for startups)
- Microsoft Imagine (for students)
- Newsletter
- Privacy & cookies
- Terms of use
- Trademarks
© 2023 Microsoft
Should I use _T or _TEXT on C++ string literals?
I’ve seen both. _T seems to be for brevity and _TEXT for clarity. Is this merely a subjective programmer preference or is it more technical than that? For instance, if I use one over the other, will my code not compile against a particular system or some older version of a header file?
8 Answers 8
A simple grep of the SDK shows us that the answer is that it doesn’t matter—they are the same. They both turn into __T(x) .
And for completeness:
However, technically, for C++ you should be using TEXT() instead of _TEXT() , but it (eventually) expands to the same thing too.
Commit to Unicode and just use L»My String Literal» .
TEXT vs. _TEXT vs. _T, and UNICODE vs. _UNICODE
The plain versions without the underscore affect the character set the Windows header files treat as default. So if you define UNICODE, then GetWindowText will map to GetWindowTextW instead of GetWindowTextA, for example. Similarly, the TEXT macro will map to L". " instead of ". ".
The versions with the underscore affect the character set the C runtime header files treat as default. So if you define _UNICODE, then _tcslen will map to wcslen instead of strlen, for example. Similarly, the _TEXT macro will map to L". " instead of ". ".
What about _T? Okay, I don’t know about that one. Maybe it was just to save somebody some typing.
Short version: _T() is a lazy man’s _TEXT()
Note: You need to be aware of what code-page your source code text editor is using when you write:
Строки
С точки зрения регулярного программирования строковый тип данных string относится к числу самых важных в C#. Этот тип определяет и поддерживает символьные строки. В целом ряде других языков программирования строка представляет собой массив символов. А в C# строки являются объектами. Следовательно, тип string относится к числу ссылочных.
Построение строк
Самый простой способ построить символьную строку — воспользоваться строковым литералом. Например, в следующей строке кода переменной ссылки на строку str присваивается ссылка на строковый литерал:
В данном случае переменная str инициализируется последовательностью символов «Пример строки». Объект типа string можно также создать из массива типа char. Например:
Как только объект типа string будет создан, его можно использовать везде, где только требуется строка текста, заключенного в кавычки.
Постоянство строк
Как ни странно, содержимое объекта типа string не подлежит изменению. Это означает, что однажды созданную последовательность символов изменить нельзя. Но данное ограничение способствует более эффективной реализации символьных строк. Поэтому этот, на первый взгляд, очевидный недостаток на самом деле превращается в преимущество. Так, если требуется строка в качестве разновидности уже имеющейся строки, то для этой цели следует создать новую строку, содержащую все необходимые изменения. А поскольку неиспользуемые строковые объекты автоматически собираются в «мусор», то о дальнейшей судьбе ненужных строк можно даже не беспокоиться.
Следует, однако, подчеркнуть, что переменные ссылки на строки (т.е. объекты типа string) подлежат изменению, а следовательно, они могут ссылаться на другой объект. Но содержимое самого объекта типа string не меняется после его создания.
Скомпилируем приложение и загрузим результирующую сборку в утилиту ildasm.exe. На рисунке показан CIL-код, который будет сгенерирован для метода void addNewString():
Обратите внимание на наличие многочисленных вызовов кода операции ldstr (загрузка строки). Этот код операции ldstr в CIL предусматривает выполнение загрузки нового объекта string в управляемую кучу. В результате предыдущий объект, в котором содержалось значение «This is my stroke», будет в конечном итоге удален сборщиком мусора.
Работа со строками
В классе System.String предоставляется набор методов для определения длины символьных данных, поиска подстроки в текущей строке, преобразования символов из верхнего регистра в нижний и наоборот, и т.д. Далее мы рассмотрим этот класс более подробно.
Поле, индексатор и свойство класса String
В классе String определено единственное поле:
Поле Empty обозначает пустую строку, т.е. такую строку, которая не содержит символы. Этим оно отличается от пустой ссылки типа String, которая просто делается на несуществующий объект.
Помимо этого, в классе String определен единственный индексатор, доступный только для чтения:
Этот индексатор позволяет получить символ по указанному индексу. Индексация строк, как и массивов, начинается с нуля. Объекты типа String отличаются постоянством и не изменяются, поэтому вполне логично, что в классе String поддерживается индексатор, доступный только для чтения.
И наконец, в классе String определено единственное свойство, доступное только для чтения:
Свойство Length возвращает количество символов в строке. В примере ниже показано использование индексатора и свойства Length:
Операторы класса String
В классе String перегружаются два следующих оператора: == и !=. Оператор == служит для проверки двух символьных строк на равенство. Когда оператор == применяется к ссылкам на объекты, он обычно проверяет, делаются ли обе ссылки на один и тот же объект. А когда оператор == применяется к ссылкам на объекты типа String, то на предмет равенства сравнивается содержимое самих строк. Это же относится и к оператору !=. Когда он применяется к ссылкам на объекты типа String, то на предмет неравенства сравнивается содержимое самих строк. В то же время другие операторы отношения, в том числе =, сравнивают ссылки на объекты типа String таким же образом, как и на объекты других типов. А для того чтобы проверить, является ли одна строка больше другой, следует вызвать метод Compare(), определенный в классе String.
Как станет ясно дальше, во многих видах сравнения символьных строк используются сведения о культурной среде. Но это не относится к операторам == и !=. Ведь они просто сравнивают порядковые значения символов в строках. (Иными словами, они сравнивают двоичные значения символов, не видоизмененные нормами культурной среды, т.е. региональными стандартами.) Следовательно, эти операторы выполняют сравнение строк без учета регистра и настроек культурной среды.
Методы класса String
В следующей таблице перечислены некоторые наиболее интересные методы этого класса, сгруппированные по назначению:
public static int Compare(string strA, string strB, bool ignoreCase)
public static int Compare(string strA, string strB, StringComparison comparisonType)
public static int Compare(string strA, string strB, bool ignoreCase, CultureInfo culture)
Статический метод, сравнивает строку strA со строкой strB. Возвращает положительное значение, если строка strA больше строки strB; отрицательное значение, если строка strA меньше строки strB; и нуль, если строки strA и strB равны. Сравнение выполняется с учетом регистра и культурной среды.
Если параметр ignoreCase принимает логическое значение true, то при сравнении не учитываются различия между прописным и строчным вариантами букв. В противном случае эти различия учитываются.
Параметр comparisonType определяет конкретный способ сравнения строк. Класс CultureInfo определен в пространстве имен System.Globalization.
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase)
public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType)
Сравнивает части строк strA и strB. Сравнение начинается со строковых элементов strA[indexA] и strB[indexB] и включает количество символов, определяемых параметром length. Метод возвращает положительное значение, если часть строки strA больше части строки strB; отрицательное значение, если часть строки strA меньше части строки strB; и нуль, если сравниваемые части строк strA и strB равны. Сравнение выполняется с учетом регистра и культурной среды.
Делает то же, что и метод Compare(), но без учета локальных установок
Сравнивает вызывающую строку со строковым представлением объекта value. Возвращает положительное значение, если вызывающая строка больше строки value; отрицательное значение, если вызывающая строка меньше строки value; и нуль, если сравниваемые строки равны
Сравнивает вызывающую строку со строкой strB
Возвращает логическое значение true, если вызывающая строка содержит ту же последовательность символов, что и строковое представление объекта obj. Выполняется порядковое сравнение с учетом регистра, но без учета культурной среды
Возвращает логическое значение true, если вызывающая строка содержит ту же последовательность символов, что и строка value. Выполняется порядковое сравнение с учетом регистра, но без учета культурной среды. Параметр comparisonType определяет конкретный способ сравнения строк
Возвращает логическое значение true, если строка a содержит ту же последовательность символов, что и строка b . Выполняется порядковое сравнение с учетом регистра, но без учета культурной среды. Параметр comparisonType определяет конкретный способ сравнения строк
Возвращает логическое значение true, если вызывающая строка начинается с подстроки value. В противном случае возвращается логическое значение false. Параметр comparisonType определяет конкретный способ выполнения поиска
Возвращает логическое значение true, если вызывающая строка оканчивается подстрокой value. В противном случае возвращает логическое значение false. Параметр comparisonType определяет конкретный способ поиска
Находит первое вхождение заданной подстроки или символа в строке. Если искомый символ или подстрока не обнаружены, то возвращается значение -1
public int IndexOf(string value, int startIndex)
public int IndexOf(char value, int startIndex, int count)
Возвращает индекс первого вхождения символа или подстроки value в вызывающей строке. Поиск начинается с элемента, указываемого по индексу startIndex, и охватывает число элементов, определяемых параметром count (если указан). Метод возвращает значение -1, если искомый символ или подстрока не обнаружен
То же, что IndexOf, но находит последнее вхождение символа или подстроки, а не первое
public int IndexOfAny(char[] anyOf, int startIndex)
Возвращает индекс первого вхождения любого символа из массива anyOf, обнаруженного в вызывающей строке. Поиск начинается с элемента, указываемого по индексу startIndex, и охватывает число элементов, определяемых параметром count (если они указаны). Метод возвращает значение -1, если не обнаружено совпадение ни с одним из символов из массива anyOf. Поиск осуществляется порядковым способом
Возвращает индекс последнего вхождения любого символа из массива anyOf, обнаруженного в вызывающей строке
Метод, возвращающий массив string с присутствующими в данном экземпляре подстроками внутри, которые отделяются друг от друга элементами из указанного массива char или string.
В первой форме метода Split() вызывающая строка разделяется на составные части. В итоге возвращается массив, содержащий подстроки, полученные из вызывающей строки. Символы, ограничивающие эти подстроки, передаются в массиве separator. Если массив separator пуст или ссылается на пустую строку, то в качестве разделителя подстрок используется пробел. А во второй форме данного метода возвращается количество подстрок, определяемых параметром count.
public string[] Split(string[] separator, StringSplitOptions options)
public string[] Split(params char[] separator, int count, StringSplitOptions options)
В двух первых формах метода Split() вызывающая строка разделяется на части и возвращается массив, содержащий подстроки, полученные из вызывающей строки. Символы, разделяющие эти подстроки, передаются в массиве separator. Если массив separator пуст, то в качестве разделителя используется пробел. А в третьей и четвертой формах данного метода возвращается количество строк, ограничиваемое параметром count.
Но во всех формах параметр options обозначает конкретный способ обработки пустых строк, которые образуются в том случае, если два разделителя оказываются рядом. В перечислении StringSplitOptions определяются только два значения: None и RemoveEmptyEntries. Если параметр options принимает значение None, то пустые строки включаются в конечный результат разделения исходной строки. А если параметр options принимает значение RemoveEmptyEntries, то пустые строки исключаются из конечного результата разделения исходной строки.
Строит новую строку, комбинируя содержимое массива строк.
В первой форме метода Join() возвращается строка, состоящая из сцепляемых подстрок, передаваемых в массиве value. Во второй форме также возвращается строка, состоящая из подстрок, передаваемых в массиве value, но они сцепляются в определенном количестве count, начиная с элемента массива value[startIndex]. В обеих формах каждая последующая строка отделяется от предыдущей разделительной строкой, определяемой параметром separator.
Метод, который позволяет удалять все вхождения определенного набора символов с начала и конца текущей строки.
В первой форме метода Trim() из вызывающей строки удаляются начальные и конечные пробелы. А во второй форме этого метода удаляются начальные и конечные вхождения в вызывающей строке символов из массива trimChars. В обеих формах возвращается получающаяся в итоге строка.
Позволяет дополнить строку символами слева.
Позволяет дополнить строку символами справа.
Используется для вставки одной строки в другую, где value обозначает строку, вставляемую в вызывающую строку по индексу startIndex. Метод возвращает получившуюся в итоге строку.
Используется для удаления части строки. В первой форме метода Remove() удаление выполняется, начиная с места, указываемого по индексу startIndex, и продолжается до конца строки. А во второй форме данного метода из строки удаляется количество символов, определяемое параметром count, начиная с места, указываемого по индексу startIndex.
Используется для замены части строки. В первой форме метода Replace() все вхождения символа oldChar в вызывающей строке заменяются символом newChar. А во второй форме данного метода все вхождения строки oldValue в вызывающей строке заменяются строкой newValue.
Делает заглавными все буквы в вызывающей строке.
Делает строчными все буквы в вызывающей строке.
В первой форме метода Substring() подстрока извлекается, начиная с места, обозначаемого параметром startIndex, и до конца вызывающей строки. А во второй форме данного метода извлекается подстрока, состоящая из количества символов, определяемых параметром length, начиная с места, обозначаемого параметром startIndex.
Пример следующей программы использует несколько из вышеуказанных методов:
Немного о сравнении строк в C#
Вероятно, из всех операций обработки символьных строк чаще всего выполняется сравнение одной строки с другой. Прежде чем рассматривать какие-либо методы сравнения строк, следует подчеркнуть следующее: сравнение строк может быть выполнено в среде .NET Framework двумя основными способами:
Во-первых, сравнение может отражать обычаи и нормы отдельной культурной среды, которые зачастую представляют собой настройки культурной среды, вступающие в силу при выполнении программы. Это стандартное поведение некоторых, хотя и не всех методов сравнения.
И во-вторых, сравнение может быть выполнено независимо от настроек культурной среды только по порядковым значениям символов, составляющих строку. Вообще говоря, при сравнении строк без учета культурной среды используется лексикографический порядок (и лингвистические особенности), чтобы определить, является ли одна строка больше, меньше или равной другой строке. При порядковом сравнении строки просто упорядочиваются на основании невидоизмененного значения каждого символа.
В силу отличий способов сравнения строк с учетом культурной среды и порядкового сравнения, а также последствий каждого такого сравнения настоятельно рекомендуется руководствоваться лучшими методиками, предлагаемыми в настоящее время корпорацией Microsoft. Ведь выбор неверного способа сравнения строк может привести к неправильной работе программы, когда она эксплуатируется в среде, отличающей от той, в которой она разработана.
Выбор способа сравнения символьных строк представляет собой весьма ответственное решение. Как правило и без всяких исключений, следует выбирать сравнение строк с учетом культурной среды, если это делается для целей отображения результата пользователю (например, для вывода на экран ряда строк, отсортированных в лексикографическом порядке). Но если строки содержат фиксированную информацию, не предназначенную для видоизменения с учетом отличий в культурных средах, например, имя файла, ключевое слово, адрес веб-сайта или значение, связанное с обеспечением безопасности, то следует выбрать порядковое сравнение строк. Разумеется, особенности конкретного разрабатываемого приложения будут диктовать выбор подходящего способа сравнения символьных строк.
В классе String предоставляются самые разные методы сравнения строк, которые перечислены в таблице выше. Наиболее универсальным среди них является метод Compare(). Он позволяет сравнивать две строки полностью или частично, с учетом или без учета регистра, способа сравнения, определяемого параметром типа StringComparison, а также сведений о культурной среде, предоставляемых с помощью параметра типа CultureInfo.
Те перегружаемые варианты метода Compare(), которые не содержат параметр типа StringComparison, выполняют сравнение символьных строк с учетом регистра и культурной среды. А в тех перегружаемых его вариантах, которые не содержат параметр типа CultureInfo, сведения о культурной среде определяются текущей средой выполнения.
Тип StringComparison представляет собой перечисление, в котором определяются значения, приведенные в таблице ниже. Используя эти значения, можно организовать сравнение строк, удовлетворяющее потребностям конкретного приложения. Следовательно, добавление параметра типа StringComparison расширяет возможности метода Compare() и других методов сравнения, например, Equals(). Это дает также возможность однозначно указывать способ предполагаемого сравнения строк.
В силу имеющих отличий между сравнением строк с учетом культурной среды и порядковым сравнением очень важно быть предельно точным в этом отношении.
Значение | Описание |
---|---|
CurrentCulture | Сравнение строк производится с использованием текущих настроек параметров культурной среды |
CurrentCultureIgnoreCase | Сравнение строк производится с использованием текущих настроек параметров культурной среды, но без учета регистра |
InvariantCulture | Сравнение строк производится с использованием неизменяемых, т.е. универсальных данных о культурной среде |
InvariantCultureIgnoreCase | Сравнение строк производится с использованием неизменяемых, т.е. универсальных данных о культурной среде и без учета регистра |
Ordinal | Сравнение строк производится с использованием порядковых значений символов в строке. При этом лексикографический порядок может нарушиться, а условные обозначения, принятые в отдельной культурной среде, игнорируются |
OrdinalIgnoreCase | Сравнение строк производится с использованием порядковых значений символов в строке, но без учета регистра |
В любом случае метод Compare() возвращает отрицательное значение, если первая сравниваемая строка оказывается меньше второй; положительное значение, если первая сравниваемая строка больше второй; и наконец, нуль, если обе сравниваемые строки равны. Несмотря на то что метод Compare() возвращает нуль, если сравниваемые строки равны, для определения равенства символьных строк, как правило, лучше пользоваться методом Equals() или же оператором ==.
Дело в том, что метод Compare() определяет равенство сравниваемых строк на основании порядка их сортировки. Так, если выполняется сравнение строк с учетом культурной среды, то обе строки могут оказаться одинаковыми по порядку их сортировки, но не равными по существу. По умолчанию равенство строк определяется в методе Equals(), исходя из порядковых значений символов и без учета культурной среды. Следовательно, по умолчанию обе строки сравниваются в этом методе на абсолютное, посимвольное равенство подобно тому, как это делается в операторе ==.
Несмотря на большую универсальность метода Compare(), для простого порядкового сравнения символьных строк проще пользоваться методом CompareOrdinal(). И наконец, следует иметь в виду, что метод CompareTo() выполняет сравнение строк только с учетом культурной среды.
В приведенной ниже программе демонстрируется применение методов Compare(), Equals(), CompareOrdinal(), а также операторов == и != для сравнения символьных строк. Обратите внимание на то, что два первых примера сравнения наглядно демонстрируют отличия между сравнением строк с учетом культурной среды и порядковым сравнением в англоязычной среде:
Строки
С точки зрения регулярного программирования строковый тип данных string относится к числу самых важных в C#. Этот тип определяет и поддерживает символьные строки. В целом ряде других языков программирования строка представляет собой массив символов. А в C# строки являются объектами. Следовательно, тип string относится к числу ссылочных.
Построение строк
Самый простой способ построить символьную строку — воспользоваться строковым литералом. Например, в следующей строке кода переменной ссылки на строку str присваивается ссылка на строковый литерал:
В данном случае переменная str инициализируется последовательностью символов «Пример строки». Объект типа string можно также создать из массива типа char. Например:
Как только объект типа string будет создан, его можно использовать везде, где только требуется строка текста, заключенного в кавычки.
Постоянство строк
Как ни странно, содержимое объекта типа string не подлежит изменению. Это означает, что однажды созданную последовательность символов изменить нельзя. Но данное ограничение способствует более эффективной реализации символьных строк. Поэтому этот, на первый взгляд, очевидный недостаток на самом деле превращается в преимущество. Так, если требуется строка в качестве разновидности уже имеющейся строки, то для этой цели следует создать новую строку, содержащую все необходимые изменения. А поскольку неиспользуемые строковые объекты автоматически собираются в «мусор», то о дальнейшей судьбе ненужных строк можно даже не беспокоиться.
Следует, однако, подчеркнуть, что переменные ссылки на строки (т.е. объекты типа string) подлежат изменению, а следовательно, они могут ссылаться на другой объект. Но содержимое самого объекта типа string не меняется после его создания.
Скомпилируем приложение и загрузим результирующую сборку в утилиту ildasm.exe. На рисунке показан CIL-код, который будет сгенерирован для метода void addNewString():
Обратите внимание на наличие многочисленных вызовов кода операции ldstr (загрузка строки). Этот код операции ldstr в CIL предусматривает выполнение загрузки нового объекта string в управляемую кучу. В результате предыдущий объект, в котором содержалось значение «This is my stroke», будет в конечном итоге удален сборщиком мусора.
Работа со строками
В классе System.String предоставляется набор методов для определения длины символьных данных, поиска подстроки в текущей строке, преобразования символов из верхнего регистра в нижний и наоборот, и т.д. Далее мы рассмотрим этот класс более подробно.
Поле, индексатор и свойство класса String
В классе String определено единственное поле:
Поле Empty обозначает пустую строку, т.е. такую строку, которая не содержит символы. Этим оно отличается от пустой ссылки типа String, которая просто делается на несуществующий объект.
Помимо этого, в классе String определен единственный индексатор, доступный только для чтения:
Этот индексатор позволяет получить символ по указанному индексу. Индексация строк, как и массивов, начинается с нуля. Объекты типа String отличаются постоянством и не изменяются, поэтому вполне логично, что в классе String поддерживается индексатор, доступный только для чтения.
И наконец, в классе String определено единственное свойство, доступное только для чтения:
Свойство Length возвращает количество символов в строке. В примере ниже показано использование индексатора и свойства Length:
Операторы класса String
В классе String перегружаются два следующих оператора: == и !=. Оператор == служит для проверки двух символьных строк на равенство. Когда оператор == применяется к ссылкам на объекты, он обычно проверяет, делаются ли обе ссылки на один и тот же объект. А когда оператор == применяется к ссылкам на объекты типа String, то на предмет равенства сравнивается содержимое самих строк. Это же относится и к оператору !=. Когда он применяется к ссылкам на объекты типа String, то на предмет неравенства сравнивается содержимое самих строк. В то же время другие операторы отношения, в том числе =, сравнивают ссылки на объекты типа String таким же образом, как и на объекты других типов. А для того чтобы проверить, является ли одна строка больше другой, следует вызвать метод Compare(), определенный в классе String.
Как станет ясно дальше, во многих видах сравнения символьных строк используются сведения о культурной среде. Но это не относится к операторам == и !=. Ведь они просто сравнивают порядковые значения символов в строках. (Иными словами, они сравнивают двоичные значения символов, не видоизмененные нормами культурной среды, т.е. региональными стандартами.) Следовательно, эти операторы выполняют сравнение строк без учета регистра и настроек культурной среды.
Методы класса String
В следующей таблице перечислены некоторые наиболее интересные методы этого класса, сгруппированные по назначению:
public static int Compare(string strA, string strB, bool ignoreCase)
public static int Compare(string strA, string strB, StringComparison comparisonType)
public static int Compare(string strA, string strB, bool ignoreCase, CultureInfo culture)
Статический метод, сравнивает строку strA со строкой strB. Возвращает положительное значение, если строка strA больше строки strB; отрицательное значение, если строка strA меньше строки strB; и нуль, если строки strA и strB равны. Сравнение выполняется с учетом регистра и культурной среды.
Если параметр ignoreCase принимает логическое значение true, то при сравнении не учитываются различия между прописным и строчным вариантами букв. В противном случае эти различия учитываются.
Параметр comparisonType определяет конкретный способ сравнения строк. Класс CultureInfo определен в пространстве имен System.Globalization.
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase)
public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType)
Сравнивает части строк strA и strB. Сравнение начинается со строковых элементов strA[indexA] и strB[indexB] и включает количество символов, определяемых параметром length. Метод возвращает положительное значение, если часть строки strA больше части строки strB; отрицательное значение, если часть строки strA меньше части строки strB; и нуль, если сравниваемые части строк strA и strB равны. Сравнение выполняется с учетом регистра и культурной среды.
Делает то же, что и метод Compare(), но без учета локальных установок
Сравнивает вызывающую строку со строковым представлением объекта value. Возвращает положительное значение, если вызывающая строка больше строки value; отрицательное значение, если вызывающая строка меньше строки value; и нуль, если сравниваемые строки равны
Сравнивает вызывающую строку со строкой strB
Возвращает логическое значение true, если вызывающая строка содержит ту же последовательность символов, что и строковое представление объекта obj. Выполняется порядковое сравнение с учетом регистра, но без учета культурной среды
Возвращает логическое значение true, если вызывающая строка содержит ту же последовательность символов, что и строка value. Выполняется порядковое сравнение с учетом регистра, но без учета культурной среды. Параметр comparisonType определяет конкретный способ сравнения строк
Возвращает логическое значение true, если строка a содержит ту же последовательность символов, что и строка b . Выполняется порядковое сравнение с учетом регистра, но без учета культурной среды. Параметр comparisonType определяет конкретный способ сравнения строк
Возвращает логическое значение true, если вызывающая строка начинается с подстроки value. В противном случае возвращается логическое значение false. Параметр comparisonType определяет конкретный способ выполнения поиска
Возвращает логическое значение true, если вызывающая строка оканчивается подстрокой value. В противном случае возвращает логическое значение false. Параметр comparisonType определяет конкретный способ поиска
Находит первое вхождение заданной подстроки или символа в строке. Если искомый символ или подстрока не обнаружены, то возвращается значение -1
public int IndexOf(string value, int startIndex)
public int IndexOf(char value, int startIndex, int count)
Возвращает индекс первого вхождения символа или подстроки value в вызывающей строке. Поиск начинается с элемента, указываемого по индексу startIndex, и охватывает число элементов, определяемых параметром count (если указан). Метод возвращает значение -1, если искомый символ или подстрока не обнаружен
То же, что IndexOf, но находит последнее вхождение символа или подстроки, а не первое
public int IndexOfAny(char[] anyOf, int startIndex)
Возвращает индекс первого вхождения любого символа из массива anyOf, обнаруженного в вызывающей строке. Поиск начинается с элемента, указываемого по индексу startIndex, и охватывает число элементов, определяемых параметром count (если они указаны). Метод возвращает значение -1, если не обнаружено совпадение ни с одним из символов из массива anyOf. Поиск осуществляется порядковым способом
Возвращает индекс последнего вхождения любого символа из массива anyOf, обнаруженного в вызывающей строке
Метод, возвращающий массив string с присутствующими в данном экземпляре подстроками внутри, которые отделяются друг от друга элементами из указанного массива char или string.
В первой форме метода Split() вызывающая строка разделяется на составные части. В итоге возвращается массив, содержащий подстроки, полученные из вызывающей строки. Символы, ограничивающие эти подстроки, передаются в массиве separator. Если массив separator пуст или ссылается на пустую строку, то в качестве разделителя подстрок используется пробел. А во второй форме данного метода возвращается количество подстрок, определяемых параметром count.
public string[] Split(string[] separator, StringSplitOptions options)
public string[] Split(params char[] separator, int count, StringSplitOptions options)
В двух первых формах метода Split() вызывающая строка разделяется на части и возвращается массив, содержащий подстроки, полученные из вызывающей строки. Символы, разделяющие эти подстроки, передаются в массиве separator. Если массив separator пуст, то в качестве разделителя используется пробел. А в третьей и четвертой формах данного метода возвращается количество строк, ограничиваемое параметром count.
Но во всех формах параметр options обозначает конкретный способ обработки пустых строк, которые образуются в том случае, если два разделителя оказываются рядом. В перечислении StringSplitOptions определяются только два значения: None и RemoveEmptyEntries. Если параметр options принимает значение None, то пустые строки включаются в конечный результат разделения исходной строки. А если параметр options принимает значение RemoveEmptyEntries, то пустые строки исключаются из конечного результата разделения исходной строки.
Строит новую строку, комбинируя содержимое массива строк.
В первой форме метода Join() возвращается строка, состоящая из сцепляемых подстрок, передаваемых в массиве value. Во второй форме также возвращается строка, состоящая из подстрок, передаваемых в массиве value, но они сцепляются в определенном количестве count, начиная с элемента массива value[startIndex]. В обеих формах каждая последующая строка отделяется от предыдущей разделительной строкой, определяемой параметром separator.
Метод, который позволяет удалять все вхождения определенного набора символов с начала и конца текущей строки.
В первой форме метода Trim() из вызывающей строки удаляются начальные и конечные пробелы. А во второй форме этого метода удаляются начальные и конечные вхождения в вызывающей строке символов из массива trimChars. В обеих формах возвращается получающаяся в итоге строка.
Позволяет дополнить строку символами слева.
Позволяет дополнить строку символами справа.
Используется для вставки одной строки в другую, где value обозначает строку, вставляемую в вызывающую строку по индексу startIndex. Метод возвращает получившуюся в итоге строку.
Используется для удаления части строки. В первой форме метода Remove() удаление выполняется, начиная с места, указываемого по индексу startIndex, и продолжается до конца строки. А во второй форме данного метода из строки удаляется количество символов, определяемое параметром count, начиная с места, указываемого по индексу startIndex.
Используется для замены части строки. В первой форме метода Replace() все вхождения символа oldChar в вызывающей строке заменяются символом newChar. А во второй форме данного метода все вхождения строки oldValue в вызывающей строке заменяются строкой newValue.
Делает заглавными все буквы в вызывающей строке.
Делает строчными все буквы в вызывающей строке.
В первой форме метода Substring() подстрока извлекается, начиная с места, обозначаемого параметром startIndex, и до конца вызывающей строки. А во второй форме данного метода извлекается подстрока, состоящая из количества символов, определяемых параметром length, начиная с места, обозначаемого параметром startIndex.
Пример следующей программы использует несколько из вышеуказанных методов:
Немного о сравнении строк в C#
Вероятно, из всех операций обработки символьных строк чаще всего выполняется сравнение одной строки с другой. Прежде чем рассматривать какие-либо методы сравнения строк, следует подчеркнуть следующее: сравнение строк может быть выполнено в среде .NET Framework двумя основными способами:
Во-первых, сравнение может отражать обычаи и нормы отдельной культурной среды, которые зачастую представляют собой настройки культурной среды, вступающие в силу при выполнении программы. Это стандартное поведение некоторых, хотя и не всех методов сравнения.
И во-вторых, сравнение может быть выполнено независимо от настроек культурной среды только по порядковым значениям символов, составляющих строку. Вообще говоря, при сравнении строк без учета культурной среды используется лексикографический порядок (и лингвистические особенности), чтобы определить, является ли одна строка больше, меньше или равной другой строке. При порядковом сравнении строки просто упорядочиваются на основании невидоизмененного значения каждого символа.
В силу отличий способов сравнения строк с учетом культурной среды и порядкового сравнения, а также последствий каждого такого сравнения настоятельно рекомендуется руководствоваться лучшими методиками, предлагаемыми в настоящее время корпорацией Microsoft. Ведь выбор неверного способа сравнения строк может привести к неправильной работе программы, когда она эксплуатируется в среде, отличающей от той, в которой она разработана.
Выбор способа сравнения символьных строк представляет собой весьма ответственное решение. Как правило и без всяких исключений, следует выбирать сравнение строк с учетом культурной среды, если это делается для целей отображения результата пользователю (например, для вывода на экран ряда строк, отсортированных в лексикографическом порядке). Но если строки содержат фиксированную информацию, не предназначенную для видоизменения с учетом отличий в культурных средах, например, имя файла, ключевое слово, адрес веб-сайта или значение, связанное с обеспечением безопасности, то следует выбрать порядковое сравнение строк. Разумеется, особенности конкретного разрабатываемого приложения будут диктовать выбор подходящего способа сравнения символьных строк.
В классе String предоставляются самые разные методы сравнения строк, которые перечислены в таблице выше. Наиболее универсальным среди них является метод Compare(). Он позволяет сравнивать две строки полностью или частично, с учетом или без учета регистра, способа сравнения, определяемого параметром типа StringComparison, а также сведений о культурной среде, предоставляемых с помощью параметра типа CultureInfo.
Те перегружаемые варианты метода Compare(), которые не содержат параметр типа StringComparison, выполняют сравнение символьных строк с учетом регистра и культурной среды. А в тех перегружаемых его вариантах, которые не содержат параметр типа CultureInfo, сведения о культурной среде определяются текущей средой выполнения.
Тип StringComparison представляет собой перечисление, в котором определяются значения, приведенные в таблице ниже. Используя эти значения, можно организовать сравнение строк, удовлетворяющее потребностям конкретного приложения. Следовательно, добавление параметра типа StringComparison расширяет возможности метода Compare() и других методов сравнения, например, Equals(). Это дает также возможность однозначно указывать способ предполагаемого сравнения строк.
В силу имеющих отличий между сравнением строк с учетом культурной среды и порядковым сравнением очень важно быть предельно точным в этом отношении.
Значение | Описание |
---|---|
CurrentCulture | Сравнение строк производится с использованием текущих настроек параметров культурной среды |
CurrentCultureIgnoreCase | Сравнение строк производится с использованием текущих настроек параметров культурной среды, но без учета регистра |
InvariantCulture | Сравнение строк производится с использованием неизменяемых, т.е. универсальных данных о культурной среде |
InvariantCultureIgnoreCase | Сравнение строк производится с использованием неизменяемых, т.е. универсальных данных о культурной среде и без учета регистра |
Ordinal | Сравнение строк производится с использованием порядковых значений символов в строке. При этом лексикографический порядок может нарушиться, а условные обозначения, принятые в отдельной культурной среде, игнорируются |
OrdinalIgnoreCase | Сравнение строк производится с использованием порядковых значений символов в строке, но без учета регистра |
В любом случае метод Compare() возвращает отрицательное значение, если первая сравниваемая строка оказывается меньше второй; положительное значение, если первая сравниваемая строка больше второй; и наконец, нуль, если обе сравниваемые строки равны. Несмотря на то что метод Compare() возвращает нуль, если сравниваемые строки равны, для определения равенства символьных строк, как правило, лучше пользоваться методом Equals() или же оператором ==.
Дело в том, что метод Compare() определяет равенство сравниваемых строк на основании порядка их сортировки. Так, если выполняется сравнение строк с учетом культурной среды, то обе строки могут оказаться одинаковыми по порядку их сортировки, но не равными по существу. По умолчанию равенство строк определяется в методе Equals(), исходя из порядковых значений символов и без учета культурной среды. Следовательно, по умолчанию обе строки сравниваются в этом методе на абсолютное, посимвольное равенство подобно тому, как это делается в операторе ==.
Несмотря на большую универсальность метода Compare(), для простого порядкового сравнения символьных строк проще пользоваться методом CompareOrdinal(). И наконец, следует иметь в виду, что метод CompareTo() выполняет сравнение строк только с учетом культурной среды.
В приведенной ниже программе демонстрируется применение методов Compare(), Equals(), CompareOrdinal(), а также операторов == и != для сравнения символьных строк. Обратите внимание на то, что два первых примера сравнения наглядно демонстрируют отличия между сравнением строк с учетом культурной среды и порядковым сравнением в англоязычной среде:
Text c что это
Конкатенация строк или объединение может производиться как с помощью операции + , так и с помощью метода Concat :
Метод Concat является статическим методом класса string, принимающим в качестве параметров две строки. Также имеются другие версии метода, принимающие другое количество параметров.
Для объединения строк также может использоваться метод Join :
Метод Join также является статическим. Использованная выше версия метода получает два параметра: строку-разделитель (в данном случае пробел) и массив строк, которые будут соединяться и разделяться разделителем.
Сравнение строк
Для сравнения строк применяется статический метод Compare :
Данная версия метода Compare принимает две строки и возвращает число. Если первая строка по алфавиту стоит выше второй, то возвращается число меньше нуля. В противном случае возвращается число больше нуля. И третий случай — если строки равны, то возвращается число 0.
В данном случае так как символ h по алфавиту стоит выше символа w, то и первая строка будет стоять выше.
Поиск в строке
С помощью метода IndexOf мы можем определить индекс первого вхождения отдельного символа или подстроки в строке:
Подобным образом действует метод LastIndexOf , только находит индекс последнего вхождения символа или подстроки в строку.
Еще одна группа методов позволяет узнать начинается или заканчивается ли строка на определенную подстроку. Для этого предназначены методы StartsWith и EndsWith . Например, в массиве строк хранится список файлов, и нам надо вывести все файлы с расширением exe:
Разделение строк
С помощью функции Split мы можем разделить строку на массив подстрок. В качестве параметра функция Split принимает массив символов или строк, которые и будут служить разделителями. Например, подсчитаем количество слов в сроке, разделив ее по пробельным символам:
Это не лучший способ разделения по пробелам, так как во входной строке у нас могло бы быть несколько подряд идущих пробелов и в итоговый массив также бы попадали пробелы, поэтому лучше использовать другую версию метода:
Второй параметр StringSplitOptions.RemoveEmptyEntries говорит, что надо удалить все пустые подстроки.
Обрезка строки
Для обрезки начальных или концевых символов используется функция Trim :
Функция Trim без параметров обрезает начальные и конечные пробелы и возвращает обрезанную строку. Чтобы явным образом указать, какие начальные и конечные символы следует обрезать, мы можем передать в функцию массив этих символов.
Эта функция имеет частичные аналоги: функция TrimStart обрезает начальные символы, а функция TrimEnd обрезает конечные символы.
Обрезать определенную часть строки позволяет функция Substring :
Функция Substring также возвращает обрезанную строку. В качестве параметра первая использованная версия применяет индекс, начиная с которого надо обрезать строку. Вторая версия применяет два параметра — индекс начала обрезки и длину вырезаемой части строки.
Вставка
Для вставки одной строки в другую применяется функция Insert :
Первым параметром в функции Insert является индекс, по которому надо вставлять подстроку, а второй параметр — собственно подстрока.
Удаление строк
Удалить часть строки помогает метод Remove :
Первая версия метода Remove принимает индекс в строке, начиная с которого надо удалить все символы. Вторая версия принимает еще один параметр — сколько символов надо удалить.
Замена
Чтобы заменить один символ или подстроку на другую, применяется метод Replace :
Во втором случае применения функции Replace строка из одного символа «о» заменяется на пустую строку, то есть фактически удаляется из текста. Подобным способом легко удалять какой-то определенный текст в строках.
Смена регистра
Для приведения строки к верхнему и нижнему регистру используются соответственно функции ToUpper() и ToLower() :
Функции обработки строк в Cи
В программе строки могут определяться следующим образом:
- как строковые константы;
- как массивы символов;
- через указатель на символьный тип;
- как массивы строк.
Кроме того, должно быть предусмотрено выделение памяти для хранения строки.
Любая последовательность символов, заключенная в двойные кавычки «» , рассматривается как строковая константа .
Для корректного вывода любая строка должна заканчиваться нуль-символом '\0' , целочисленное значение которого равно 0. При объявлении строковой константы нуль-символ добавляется к ней автоматически. Так, последовательность символов, представляющая собой строковую константу, будет размещена в оперативной памяти компьютера, включая нулевой байт.
Под хранение строки выделяются последовательно идущие ячейки оперативной памяти. Таким образом, строка представляет собой массив символов. Для хранения кода каждого символа строки отводится 1 байт.
Для помещения в строковую константу некоторых служебных символов используются символьные комбинации. Так, если необходимо включить в строку символ двойной кавычки, ему должен предшествовать символ «обратный слеш»: ‘\»‘ .
Строковые константы размещаются в статической памяти. Начальный адрес последовательности символов в двойных кавычках трактуется как адрес строки. Строковые константы часто используются для осуществления диалога с пользователем в таких функциях, как printf() .
При определении массива символов необходимо сообщить компилятору требуемый размер памяти.
Компилятор также может самостоятельно определить размер массива символов, если инициализация массива задана при объявлении строковой константой:
В этом случае имена m2 и m3 являются указателями на первые элементы массивов:
- m2 эквивалентно &m2[0]
- m2[0] эквивалентно ‘Г’
- m2[1] эквивалентно ‘o’
- m3 эквивалентно &m3[0]
- m3[2] эквивалентно ‘x’
При объявлении массива символов и инициализации его строковой константой можно явно указать размер массива, но указанный размер массива должен быть больше, чем размер инициализирующей строковой константы:
Для задания строки можно использовать указатель на символьный тип .
В этом случае объявление массива переменной m4 может быть присвоен адрес массива:
Здесь m3 является константой-указателем. Нельзя изменить m3 , так как это означало бы изменение положения (адреса) массива в памяти, в отличие от m4 .
Для указателя можно использовать операцию увеличения (перемещения на следующий символ):
Массивы символьных строк
Иногда в программах возникает необходимость описание массива символьных строк . В этом случае можно использовать индекс строки для доступа к нескольким разным строкам.
В этом случае poet является массивом, состоящим из четырех указателей на символьные строки. Каждая строка символов представляет собой символьный массив, поэтому имеется четыре указателя на массивы. Указатель poet[0] ссылается на первую строку:
*poet[0] эквивалентно 'П',
*poet[l] эквивалентно '-'.
Инициализация выполняется по правилам, определенным для массивов.
Тексты в кавычках эквивалентны инициализации каждой строки в массиве. Запятая разделяет соседние
последовательности.
Кроме того, можно явно задавать размер строк символов, используя описание, подобное такому:
Разница заключается в том, что такая форма задает «прямоугольный» массив, в котором все строки имеют одинаковую длину.
Свободный массив
Операции со строками
Большинство операций языка Си, имеющих дело со строками, работает с указателями. Для размещения в оперативной памяти строки символов необходимо:
- выделить блок оперативной памяти под массив;
- проинициализировать строку.
Для выделения памяти под хранение строки могут использоваться функции динамического выделения памяти. При этом необходимо учитывать требуемый размер строки:
Для ввода строки использована функция scanf() , причем введенная строка не может превышать 9 символов. Последний символ будет содержать '\0' .
Функции ввода строк
Для ввода строки может использоваться функция scanf() . Однако функция scanf() предназначена скорее для получения слова, а не строки. Если применять формат "%s" для ввода, строка вводится до (но не включая) следующего пустого символа, которым может быть пробел, табуляция или перевод строки.
Для ввода строки, включая пробелы, используется функция
В качестве аргумента функции передается указатель на строку, в которую осуществляется ввод. Функция просит пользователя ввести строку, которую она помещает в массив, пока пользователь не нажмет Enter.
Функции вывода строк
Для вывода строк можно воспользоваться рассмотренной ранее функцией
или в сокращенном формате
Для вывода строк также может использоваться функция
которая печатает строку s и переводит курсор на новую строку (в отличие от printf() ). Функция puts() также может использоваться для вывода строковых констант, заключенных в кавычки.
Функция ввода символов
Для ввода символов может использоваться функция
которая возвращает значение символа, введенного с клавиатуры. Указанная функция использовалась в рассмотренных ранее примерах для задержки окна консоли после выполнения программы до нажатия клавиши.
Функция вывода символов
Для вывода символов может использоваться функция
которая возвращает значение выводимого символа и выводит на экран символ, переданный в качестве аргумента.
Пример Посчитать количество введенных символов во введенной строке.
Результат выполнения
C#. Урок 5. Работа со строками
Тема работы со строками является одной из значимых при изучении любого языка программирования. В приведенном материале будут рассмотрены как базовые концепции работы со строками, так и расширенные возможности, предоставляемые C#.
Исходный код примеров из этой статьи можете скачать из нашего github-репозитория.
Знакомство со строками в C#
За представление строк в C# отвечает класс System . String . В коде, для объявления переменной соответствующего типа, предпочтительно использовать следующий вариант написания: string – с маленькой буквы. Это ключевое слово языка, используя которое можно объявлять строковые переменные, также как int является псевдонимом для System.Int32 , а bool – для System.Boolean .
Допустимо объявление строковых переменных через ключевое слово var :
Для объединения строк используется оператор +:
При работе со String следует помнить, что при переопределении значения переменной создается новый экземпляр строковой переменной в памяти. Поэтому, если вам нужно собрать строку из большого количества составляющих, то использование оператора + не самый лучший вариант. В этом случае будет происходить перерасход памяти: при выполнении операции объединения с присваиванием для очень большого количества подстрок, приложение может аварийно завершиться из-за того, что сборщик мусора не будет успевать удалять неиспользуемые объекты, а новые будут продолжать появляться с большой скоростью. Для решения этой задачи используйте StringBuilder , о нем будет рассказано в конце этого урока.
Создание и инициализация объекта класса String
Существует несколько способов создать объект класса String и проинициализировать его. Рассмотрим варианты, которые доступны в C# . Наиболее распространенный способ сделать эту операцию – это присвоить строковое значение переменной без явного вызова конструктора, так, как мы это делали в предыдущем разделе:
Для дословного представления строки, для того чтобы проигнорировать управляющие последовательности, используйте префикс @ перед значением. Сравните вывод следующей конструкции:
Если требуется подготовить строковое значение с использованием набора переменных, то можно воспользоваться статическим методом Format класса String , либо префиксом $ :
Можно явно вызвать конструктор типа c передачей в него параметров. Самый простой вариант – это передать строку:
В качестве параметра может выступать массив Char элементов:
Ещё вариант – это указать элемент типа char и количество раз, которое его нужно повторить:
Для создания строки также можно использовать указатели на Char* и SByte* , но в данном уроке эта тема рассматриваться не будет.
Базовый API для работы со строками
В рамках данного раздела рассмотрим наиболее интересные и полезные методы и свойства класса String .
Объединение строк. Оператор +, методы Concat и Join
Сцеплять строки между собой можно с помощью оператора + , при этом, в результате объединения, будет создан новый объект:
В составе API , который предоставляет System . String , есть метод Concat , который может выполнять ту же работу:
Метод Concat позволяет объединить до четырех строк через прямое перечисление. Если нужно таким образом объединить больше строковых переменных и значений, то используйте оператор +. Полезным свойством Concat является то, что он может принять на вход массив элементов типа String и объединить их:
Для объединения элементов с указанием разделителя используется метод Join . В предыдущем примере, элементы в массиве sArr1 уже содержали пробел, это не всегда удобно, решим задачу объединения элементов, которые не содержат разделителей, с помощью Join :
В качестве разделителя можно использовать любую строку:
Поиск и извлечение элементов из строки. Оператор [], методы IndexOf, IndexOfAny, LastIndexOf, LastIndexOfAny, Substring
Для получения символа из строки с конкретной позиции можно использовать синтаксис подобный тому, что применяется при работе с массивами – через квадратные скобки []:
Для решения обратной задачи: поиск индекса первого (последнего) вхождения элемента или сроки в данной строке используются методы IndexOf , IndexOfAny и LastIndexOf , LastIndexOfAny .
В таблице ниже перечислены некоторые из предоставляемых System . String вариантов этих методов.
IndexOf(Char)
Возвращает индекс первого вхождения символа.
IndexOf(Char, Int32)
Возвращает индекс первого вхождения символа начиная с заданной позиции.
IndexOf(Char, Int32, Int32)
Возвращает индекс первого вхождения символа начиная с заданной позиции, проверяется указанное количество элементов.
IndexOf(String)
IndexOf(String, Int32)
IndexOf(String, Int32, Int32)
Назначение методов совпадает с перечисленными выше, но поиск выполняется для строки.
IndexOfAny(Char[])
IndexOfAny(Char[], Int32)
IndexOfAny(Char[], Int32, Int32)
Назначение методов совпадает с перечисленными выше, но выполняется поиск индекса первого вхождения любого из переданных в массиве элементов.
Last IndexOf([Char | String])
Last IndexOf ( [Char | String], Int32)
Last IndexOf ( [Char | String], Int32, Int32)
Возвращает индекс последнего вхождения символа или строки. Можно задавать индекс, с которого начинать поиск и количество проверяемых позиций. [Char | String] – означает Char или String
LastIndexOfAny(Char[])
LastIndexOfAny(Char[], Int32)
LastIndexOfAny(Char[], Int32, Int32)
Возвращает индекс последнего вхождения любого из переданных в массиве элементов.Можно задавать индекс с которого начинать поиск и количество проверяемых позиций
Для определения того, содержит ли данная строка указанную подстроку, а также для проверки равенства начала или конца строки заданному значению используйте методы: Contains , StartsWith и EndsWith .
Contains(Char)
Contains(String)
Возвращает True если строка содержит указанный символ или подстроки.
StartsWith(Char)
StartsWith(String)
Возвращает True если строка начинается с заданного символа или подстроки.
EndsWith(Char)
EndsWith(String)
Возвращает True если строка заканчивается на заданный символ или подстроку.
Задачу извлечения подстроки из данной строки решает метод SubString :
Substring(Int32)
Возвращает подстроку начиная с указанной позиции и до конца исходной строки.
Substring(Int32, Int32)
Возвращает подстроку начиная с указанной позиции с заданной длины.
Сравнение срок
Для сравнения строк можно использовать оператор сравнения ==, при этом будут сравниваться значения строковых переменных, а не их ссылки, как это делается для других ссылочных типов.
Для сравнения также можно использовать метод Equals , но это менее удобный вариант:
Модификация срок
Класс String предоставляет довольно большое количество инструментов для изменения строк.
Вставка строки в исходную в заданную позицию осуществляется с помощью метода Insert :
Для приведения строки к заданной длине с выравниванием по левому (правому) краю с заполнением недостающих символов пробелами используются методы PadLeft и PadRight :
Метод Remove удаляет подстроку из исходной строки. Возможны два варианта использования:
Remove(Int32)
Удаляет все символы начиная с заданного и до конца строки.
Remove(Int32, Int32)
Удаляет с указанной позиции заданное число символов.
Замена элементов строки производится с помощью метода Replace . Наиболее часто используемые варианты – это замена символа на символ и строки на подстроку:
Для преобразования строки к верхнему регистру используйте метод ToUpper() , к нижнему – ToLower() :
За удаление начальных и конечных символов отвечают методы, начинающиеся на Trim (см. таблицу ниже).
Удаляет символы пробелы из начала и конца строки.
Удаляет экземпляры символа из начала и конца строки.
Удаляет экземпляры символов из начала и конца строки.
TrimStart()
TrimStart(Char)
TrimStart(Char[])
Удаляет экземпляры символов из начала строки.
TrimEnd()
TrimEnd(Char)
TrimEnd(Char[])
Удаляет экземпляры символов из конца строки.
Методы и свойства общего назначения
Рассмотрим некоторые из полезных методов и свойств, которые не вошли в приведенные выше группы.
System.Length – возвращает длину строки:
System.Split() – разделяет заданную строку на подстроки, в качестве разделителя используется указанный через параметр символ (или группа символов):
System.Empty – возвращает пустую строку.
Форматирование строк
Под форматированием строк, в рамках данного раздела, понимается встраивание в строку различных элементом (число, дата и т.п.), представленных в заданном формате. Форматирование можно осуществлять с помощью метода ToString с передачей в него нужных описателей, метода Format , который, в качестве аргументов, получает строку со специальными вставками, определяющими представление элементов и непосредственно сами элементы.
Для начала рассмотрим на нескольких примерах работу с этими методоми:
Эта функциональность также доступна для методов StringBuilder . AppendFormat , TextWriter . WriteLine , Debug . WriteLine , методов из Trace , которые выводят текстовые сообщения, например: Trace . TraceError и метод TraceSource . TraceInformation .
Каждый элемент форматирования представляется следующим образом:
где index – это индекс элемента, которым будет замещена данная конструкция;
alignment – выравнивание;
formatString – формат.
Ниже приведены примеры использования элементов форматирования:
Представление чисел
Для представления чисел используются следующие описатели формата (список не полный, более детальную информацию можете найти в официальной документации):
Should I use _T or _TEXT on C++ string literals?
I’ve seen both. _T seems to be for brevity and _TEXT for clarity. Is this merely a subjective programmer preference or is it more technical than that? For instance, if I use one over the other, will my code not compile against a particular system or some older version of a header file?
8 Answers 8
A simple grep of the SDK shows us that the answer is that it doesn’t matter—they are the same. They both turn into __T(x) .
And for completeness:
However, technically, for C++ you should be using TEXT() instead of _TEXT() , but it (eventually) expands to the same thing too.
Commit to Unicode and just use L»My String Literal» .
TEXT vs. _TEXT vs. _T, and UNICODE vs. _UNICODE
The plain versions without the underscore affect the character set the Windows header files treat as default. So if you define UNICODE, then GetWindowText will map to GetWindowTextW instead of GetWindowTextA, for example. Similarly, the TEXT macro will map to L". " instead of ". ".
The versions with the underscore affect the character set the C runtime header files treat as default. So if you define _UNICODE, then _tcslen will map to wcslen instead of strlen, for example. Similarly, the _TEXT macro will map to L". " instead of ". ".
What about _T? Okay, I don’t know about that one. Maybe it was just to save somebody some typing.
Short version: _T() is a lazy man’s _TEXT()
Note: You need to be aware of what code-page your source code text editor is using when you write:
Text c что это
Методы работы с текстом находятся в классе String .
Тип string является псевдонимом класса String .
То есть когда мы пишем:
string myText = «Hello»;
мы можем использовать методы и переменные класса String .
Например, получить длину строки
int len = myText .Length;
или вызвать метод
book isSame = myText .CompareTo(«House»);
Текст В C# это последовательность символов Unicode.
Максимальный размер объекта String может составлять в памяти 2 ГБ, или около 1 миллиарда символов.
Length
CompareTo
ToLower
ToUpper
Split
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
string str1 = «Hello world!» ;
string str2 = «HE» ;
// не учитываем регистр
bool bStart = str1.StartsWith(str2, StringComparison.OrdinalIgnoreCase);
// bStart = true
Contains
IndexOf
Substring
IsNullOrEmpty
IsNullOrWhiteSpace
[]
String.Format
+
$
namespace ConsoleApplication1
<
class Program
<
static void Main( string [] args)
<
// текст
string str1 = "aaa" ;
string str2 = "aaa" ;
// равны ?
bool isEqual = str1 == str2;
// isEqual = true
>
>
>
String это класс, который представляет текст как последовательность символов Unicode.
Версия .NETFramework\v4.6.1\mscorlib.dll
Синтаксис
public sealed class String : IComparable, ICloneable, IConvertible, IEnumerable, IComparable<string>, IEnumerable<char>, IEquatable<string>
public String (char* value);
Parameters:
value:
A pointer to a null-terminated array of Unicode characters.
Exceptions:
System.ArgumentOutOfRangeException:
The current process does not have read access to all the addressed characters.
System.ArgumentException:
value specifies an array that contains an invalid Unicode character, or value
specifies an address less than 64000.
public String (char[] value);
public String (sbyte* value);
Parameters:
value:
A pointer to a null-terminated array of 8-bit signed integers.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentException:
A new instance of System.String could not be initialized using value, assuming
value is encoded in ANSI.
System.ArgumentOutOfRangeException:
The length of the new string to initialize, which is determined by the null
termination character of value, is too large to allocate.
System.AccessViolationException:
value specifies an invalid address.
public String (char c, int count);
Parameters:
c:
A Unicode character.
count:
The number of times c occurs.
Exceptions:
System.ArgumentOutOfRangeException:
count is less than zero.
public String (char* value, int startIndex, int length);
Parameters:
value:
A pointer to an array of Unicode characters.
startIndex:
The starting position within value.
length:
The number of characters within value to use.
Exceptions:
System.ArgumentOutOfRangeException:
startIndex or length is less than zero, value + startIndex cause a pointer
overflow, or the current process does not have read access to all the addressed
characters.
System.ArgumentException:
value specifies an array that contains an invalid Unicode character, or value
+ startIndex specifies an address less than 64000.
public String (char[] value, int startIndex, int length);
Parameters:
value:
An array of Unicode characters.
startIndex:
The starting position within value.
length:
The number of characters within value to use.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
startIndex or length is less than zero.-or- The sum of startIndex and length
is greater than the number of elements in value.
public String (sbyte* value, int startIndex, int length);
Parameters:
value:
A pointer to an array of 8-bit signed integers.
startIndex:
The starting position within value.
length:
The number of characters within value to use.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
startIndex or length is less than zero. -or-The address specified by value
+ startIndex is too large for the current platform; that is, the address
calculation overflowed. -or-The length of the new string to initialize is
too large to allocate.
System.ArgumentException:
The address specified by value + startIndex is less than 64K.-or- A new instance
of System.String could not be initialized using value, assuming value is
encoded in ANSI.
System.AccessViolationException:
value, startIndex, and length collectively specify an invalid address.
public String (sbyte* value, int startIndex, int length, Encoding enc);
Parameters:
value:
A pointer to an array of 8-bit signed integers.
startIndex:
The starting position within value.
length:
The number of characters within value to use.
enc:
An object that specifies how the array referenced by value is encoded. If
enc is null, ANSI encoding is assumed.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
startIndex or length is less than zero. -or-The address specified by value
+ startIndex is too large for the current platform; that is, the address
calculation overflowed. -or-The length of the new string to initialize is
too large to allocate.
System.ArgumentException:
The address specified by value + startIndex is less than 64K.-or- A new instance
of System.String could not be initialized using value, assuming value is
encoded as specified by enc.
System.AccessViolationException:
value, startIndex, and length collectively specify an invalid address.
public static readonly string Empty;
public int Length < get; >
public char this[int index] < get; >
Parameters:
index:
A position in the current string.
Exceptions:
The object at position index.
Exceptions:
System.IndexOutOfRangeException:
index is greater than or equal to the length of this object or less than
zero.
public static bool operator != (string a, string b);
Parameters:
a:
The first string to compare, or null.
b:
The second string to compare, or null.
Exceptions:
true if the value of a is different from the value of b; otherwise, false.
public static bool operator == (string a, string b);
Parameters:
a:
The first string to compare, or null.
b:
The second string to compare, or null.
Exceptions:
true if the value of a is the same as the value of b; otherwise, false.
public object Clone ();
public static int Compare (string strA, string strB);
Parameters:
strA:
The first string to compare.
strB:
The second string to compare.
Exceptions:
A 32-bit signed integer that indicates the lexical relationship between the
two comparands.Value Condition Less than zero strA precedes strB in the sort
order. Zero strA occurs in the same position as strB in the sort order. Greater
than zero strA follows strB in the sort order.
public static int Compare (string strA, string strB, bool ignoreCase);
Parameters:
strA:
The first string to compare.
strB:
The second string to compare.
ignoreCase:
true to ignore case during the comparison; otherwise, false.
Exceptions:
A 32-bit signed integer that indicates the lexical relationship between the
two comparands.Value Condition Less than zero strA precedes strB in the sort
order. Zero strA occurs in the same position as strB in the sort order. Greater
than zero strA follows strB in the sort order.
public static int Compare (string strA, string strB, StringComparison comparisonType);
Parameters:
strA:
The first string to compare.
strB:
The second string to compare.
comparisonType:
One of the enumeration values that specifies the rules to use in the comparison.
Exceptions:
A 32-bit signed integer that indicates the lexical relationship between the
two comparands.Value Condition Less than zero strA precedes strB in the sort
order. Zero strA is in the same position as strB in the sort order. Greater
than zero strA follows strB in the sort order.
Exceptions:
System.ArgumentException:
comparisonType is not a System.StringComparison value.
System.NotSupportedException:
System.StringComparison is not supported.
public static int Compare (string strA, string strB, bool ignoreCase, CultureInfo culture);
Parameters:
strA:
The first string to compare.
strB:
The second string to compare.
ignoreCase:
true to ignore case during the comparison; otherwise, false.
culture:
An object that supplies culture-specific comparison information.
Exceptions:
A 32-bit signed integer that indicates the lexical relationship between the
two comparands.Value Condition Less than zero strA precedes strB in the sort
order. Zero strA occurs in the same position as strB in the sort order. Greater
than zero strA follows strB in the sort order.
Exceptions:
System.ArgumentNullException:
culture is null.
public static int Compare (string strA, string strB, CultureInfo culture, CompareOptions options);
Parameters:
strA:
The first string to compare.
strB:
The second string to compare.
culture:
The culture that supplies culture-specific comparison information.
options:
Options to use when performing the comparison (such as ignoring case or symbols).
Exceptions:
A 32-bit signed integer that indicates the lexical relationship between strA
and strB, as shown in the following tableValueConditionLess than zerostrA
precedes strB in the sort order. ZerostrA occurs in the same position as
strB in the sort order. Greater than zerostrA follows strB in the sort order.
Exceptions:
System.ArgumentException:
options is not a System.Globalization.CompareOptions value.
System.ArgumentNullException:
culture is null.
public static int Compare (string strA, int indexA, string strB, int indexB, int length);
Parameters:
strA:
The first string to use in the comparison.
indexA:
The position of the substring within strA.
strB:
The second string to use in the comparison.
indexB:
The position of the substring within strB.
length:
The maximum number of characters in the substrings to compare.
Exceptions:
A 32-bit signed integer indicating the lexical relationship between the two
comparands.Value Condition Less than zero The substring in strA precedes
the substring in strB in the sort order. Zero The substrings occur in the
same position in the sort order, or length is zero. Greater than zero The
substring in strA follows the substring in strB in the sort order.
Exceptions:
System.ArgumentOutOfRangeException:
indexA is greater than strA.System.String.Length.-or- indexB is greater than
strB.System.String.Length.-or- indexA, indexB, or length is negative. -or-Either
indexA or indexB is null, and length is greater than zero.
public static int Compare (string strA, int indexA, string strB, int indexB, int length, bool ignoreCase);
Parameters:
strA:
The first string to use in the comparison.
indexA:
The position of the substring within strA.
strB:
The second string to use in the comparison.
indexB:
The position of the substring within strB.
length:
The maximum number of characters in the substrings to compare.
ignoreCase:
true to ignore case during the comparison; otherwise, false.
Exceptions:
A 32-bit signed integer that indicates the lexical relationship between the
two comparands.ValueCondition Less than zero The substring in strA precedes
the substring in strB in the sort order. Zero The substrings occur in the
same position in the sort order, or length is zero. Greater than zero The
substring in strA follows the substring in strB in the sort order.
Exceptions:
System.ArgumentOutOfRangeException:
indexA is greater than strA.System.String.Length.-or- indexB is greater than
strB.System.String.Length.-or- indexA, indexB, or length is negative. -or-Either
indexA or indexB is null, and length is greater than zero.
public static int Compare (string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType);
Parameters:
strA:
The first string to use in the comparison.
indexA:
The position of the substring within strA.
strB:
The second string to use in the comparison.
indexB:
The position of the substring within strB.
length:
The maximum number of characters in the substrings to compare.
comparisonType:
One of the enumeration values that specifies the rules to use in the comparison.
Exceptions:
A 32-bit signed integer that indicates the lexical relationship between the
two comparands.Value Condition Less than zero The substring in strA precedes
the substring in strB in the sort order.Zero The substrings occur in the
same position in the sort order, or the length parameter is zero. Greater
than zero The substring in strA follllows the substring in strB in the sort
order.
Exceptions:
System.ArgumentOutOfRangeException:
indexA is greater than strA.System.String.Length.-or- indexB is greater than
strB.System.String.Length.-or- indexA, indexB, or length is negative. -or-Either
indexA or indexB is null, and length is greater than zero.
System.ArgumentException:
comparisonType is not a System.StringComparison value.
public static int Compare (string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, CultureInfo culture);
Parameters:
strA:
The first string to use in the comparison.
indexA:
The position of the substring within strA.
strB:
The second string to use in the comparison.
indexB:
The position of the substring within strB.
length:
The maximum number of characters in the substrings to compare.
ignoreCase:
true to ignore case during the comparison; otherwise, false.
culture:
An object that supplies culture-specific comparison information.
Exceptions:
An integer that indicates the lexical relationship between the two comparands.Value
Condition Less than zero The substring in strA precedes the substring in
strB in the sort order. Zero The substrings occur in the same position in
the sort order, or length is zero. Greater than zero The substring in strA
follows the substring in strB in the sort order.
Exceptions:
System.ArgumentOutOfRangeException:
indexA is greater than strA.System.String.Length.-or- indexB is greater than
strB.System.String.Length.-or- indexA, indexB, or length is negative. -or-Either
strA or strB is null, and length is greater than zero.
System.ArgumentNullException:
culture is null.
public static int Compare (string strA, int indexA, string strB, int indexB, int length, CultureInfo culture, CompareOptions options);
Parameters:
strA:
The first string to use in the comparison.
indexA:
The starting position of the substring within strA.
strB:
The second string to use in the comparison.
indexB:
The starting position of the substring within strB.
length:
The maximum number of characters in the substrings to compare.
culture:
An object that supplies culture-specific comparison information.
options:
Options to use when performing the comparison (such as ignoring case or symbols).
Exceptions:
An integer that indicates the lexical relationship between the two substrings,
as shown in the following table.ValueConditionLess than zeroThe substring
in strA precedes the substring in strB in the sort order.ZeroThe substrings
occur in the same position in the sort order, or length is zero.Greater than
zeroThe substring in strA follows the substring in strB in the sort order.
Exceptions:
System.ArgumentException:
options is not a System.Globalization.CompareOptions value.
System.ArgumentOutOfRangeException:
indexA is greater than strA.Length.-or-indexB is greater than strB.Length.-or-indexA,
indexB, or length is negative.-or-Either strA or strB is null, and length
is greater than zero.
System.ArgumentNullException:
culture is null.
public static int CompareOrdinal (string strA, string strB);
Parameters:
strA:
The first string to compare.
strB:
The second string to compare.
Exceptions:
An integer that indicates the lexical relationship between the two comparands.ValueCondition
Less than zero strA is less than strB. Zero strA and strB are equal. Greater
than zero strA is greater than strB.
public static int CompareOrdinal (string strA, int indexA, string strB, int indexB, int length);
Parameters:
strA:
The first string to use in the comparison.
indexA:
The starting index of the substring in strA.
strB:
The second string to use in the comparison.
indexB:
The starting index of the substring in strB.
length:
The maximum number of characters in the substrings to compare.
Exceptions:
A 32-bit signed integer that indicates the lexical relationship between the
two comparands.ValueCondition Less than zero The substring in strA is less
than the substring in strB. Zero The substrings are equal, or length is zero.
Greater than zero The substring in strA is greater than the substring in
strB.
Exceptions:
System.ArgumentOutOfRangeException:
strA is not null and indexA is greater than strA.System.String.Length.-or-
strB is not null andindexB is greater than strB.System.String.Length.-or-
indexA, indexB, or length is negative.
public int CompareTo (object value);
Parameters:
value:
An object that evaluates to a System.String.
Exceptions:
A 32-bit signed integer that indicates whether this instance precedes, follows,
or appears in the same position in the sort order as the value parameter.Value
Condition Less than zero This instance precedes value. Zero This instance
has the same position in the sort order as value. Greater than zero This
instance follows value.-or- value is null.
Exceptions:
System.ArgumentException:
value is not a System.String.
public int CompareTo (string strB);
Parameters:
strB:
The string to compare with this instance.
Exceptions:
A 32-bit signed integer that indicates whether this instance precedes, follows,
or appears in the same position in the sort order as the strB parameter.Value
Condition Less than zero This instance precedes strB. Zero This instance
has the same position in the sort order as strB. Greater than zero This instance
follows strB.-or- strB is null.
public static string Concat (IEnumerable<string> values);
Parameters:
values:
A collection object that implements System.Collections.Generic.IEnumerable<T>
and whose generic type argument is System.String.
Exceptions:
The concatenated strings in values.
Exceptions:
System.ArgumentNullException:
values is null.
public static string Concat<T> (IEnumerable<T> values);
Parameters:
values:
A collection object that implements the System.Collections.Generic.IEnumerable<T>
interface.
Type parameters:
T:
The type of the members of values.
Exceptions:
The concatenated members in values.
Exceptions:
System.ArgumentNullException:
values is null.
public static string Concat (object arg0);
Parameters:
arg0:
The object to represent, or null.
Exceptions:
The string representation of the value of arg0, or System.String.Empty if
arg0 is null.
public static string Concat (params object[] args);
Parameters:
args:
An object array that contains the elements to concatenate.
Exceptions:
The concatenated string representations of the values of the elements in
args.
Exceptions:
System.ArgumentNullException:
args is null.
System.OutOfMemoryException:
Out of memory.
public static string Concat (params string[] values);
Parameters:
values:
An array of string instances.
Exceptions:
The concatenated elements of values.
Exceptions:
System.ArgumentNullException:
values is null.
System.OutOfMemoryException:
Out of memory.
public static string Concat (object arg0, object arg1);
Parameters:
arg0:
The first object to concatenate.
arg1:
The second object to concatenate.
Exceptions:
The concatenated string representations of the values of arg0 and arg1.
public static string Concat (string str0, string str1);
Parameters:
str0:
The first string to concatenate.
str1:
The second string to concatenate.
Exceptions:
The concatenation of str0 and str1.
public static string Concat (object arg0, object arg1, object arg2);
Parameters:
arg0:
The first object to concatenate.
arg1:
The second object to concatenate.
arg2:
The third object to concatenate.
Exceptions:
The concatenated string representations of the values of arg0, arg1, and
arg2.
public static string Concat (string str0, string str1, string str2);
Parameters:
str0:
The first string to concatenate.
str1:
The second string to concatenate.
str2:
The third string to concatenate.
Exceptions:
The concatenation of str0, str1, and str2.
public static string Concat (object arg0, object arg1, object arg2, object arg3);
Parameters:
arg0:
The first object to concatenate.
arg1:
The second object to concatenate.
arg2:
The third object to concatenate.
arg3:
The fourth object to concatenate.
Exceptions:
The concatenated string representation of each value in the parameter list.
public static string Concat (string str0, string str1, string str2, string str3);
Parameters:
str0:
The first string to concatenate.
str1:
The second string to concatenate.
str2:
The third string to concatenate.
str3:
The fourth string to concatenate.
Exceptions:
The concatenation of str0, str1, str2, and str3.
public bool Contains (string value);
Parameters:
value:
The string to seek.
Exceptions:
true if the value parameter occurs within this string, or if value is the
empty string («»); otherwise, false.
Exceptions:
System.ArgumentNullException:
value is null.
public static string Copy (string str);
Parameters:
str:
The string to copy.
Exceptions:
A new string with the same value as str.
Exceptions:
System.ArgumentNullException:
str is null.
public void CopyTo (int sourceIndex, char[] destination, int destinationIndex, int count);
Parameters:
sourceIndex:
The index of the first character in this instance to copy.
destination:
An array of Unicode characters to which characters in this instance are copied.
destinationIndex:
The index in destination at which the copy operation begins.
count:
The number of characters in this instance to copy to destination.
Exceptions:
System.ArgumentNullException:
destination is null.
System.ArgumentOutOfRangeException:
sourceIndex, destinationIndex, or count is negative -or- sourceIndex does
not identify a position in the current instance. -or-destinationIndex does
not identify a valid index in the destination array. -or-count is greater
than the length of the substring from startIndex to the end of this instance
-or- count is greater than the length of the subarray from destinationIndex
to the end of the destination array.
public bool EndsWith (string value);
Parameters:
value:
The string to compare to the substring at the end of this instance.
Exceptions:
true if value matches the end of this instance; otherwise, false.
Exceptions:
System.ArgumentNullException:
value is null.
public bool EndsWith (string value, StringComparison comparisonType);
Parameters:
value:
The string to compare to the substring at the end of this instance.
comparisonType:
One of the enumeration values that determines how this string and value are
compared.
Exceptions:
true if the value parameter matches the end of this string; otherwise, false.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentException:
comparisonType is not a System.StringComparison value.
public bool EndsWith (string value, bool ignoreCase, CultureInfo culture);
Parameters:
value:
The string to compare to the substring at the end of this instance.
ignoreCase:
true to ignore case during the comparison; otherwise, false.
culture:
Cultural information that determines how this instance and value are compared.
If culture is null, the current culture is used.
Exceptions:
true if the value parameter matches the end of this string; otherwise, false.
Exceptions:
System.ArgumentNullException:
value is null.
public override bool Equals (object obj);
Parameters:
obj:
The string to compare to this instance.
Exceptions:
true if obj is a System.String and its value is the same as this instance;
otherwise, false. If obj is null, the method returns false.
public bool Equals (string value);
Parameters:
value:
The string to compare to this instance.
Exceptions:
true if the value of the value parameter is the same as the value of this
instance; otherwise, false. If value is null, the method returns false.
public static bool Equals (string a, string b);
Parameters:
a:
The first string to compare, or null.
b:
The second string to compare, or null.
Exceptions:
true if the value of a is the same as the value of b; otherwise, false. If
both a and b are null, the method returns true.
public bool Equals (string value, StringComparison comparisonType);
Parameters:
value:
The string to compare to this instance.
comparisonType:
One of the enumeration values that specifies how the strings will be compared.
Exceptions:
true if the value of the value parameter is the same as this string; otherwise,
false.
Exceptions:
System.ArgumentException:
comparisonType is not a System.StringComparison value.
public static bool Equals (string a, string b, StringComparison comparisonType);
Parameters:
a:
The first string to compare, or null.
b:
The second string to compare, or null.
comparisonType:
One of the enumeration values that specifies the rules for the comparison.
Exceptions:
true if the value of the a parameter is equal to the value of the b parameter;
otherwise, false.
Exceptions:
System.ArgumentException:
comparisonType is not a System.StringComparison value.
public static string Format (string format, object arg0);
Parameters:
format:
A composite format string.
arg0:
The object to format.
Exceptions:
A copy of format in which any format items are replaced by the string representation
of arg0.
Exceptions:
System.ArgumentNullException:
format is null.
System.FormatException:
The format item in format is invalid.-or- The index of a format item is not
zero.
public static string Format (string format, params object[] args);
Parameters:
format:
A composite format string.
args:
An object array that contains zero or more objects to format.
Exceptions:
A copy of format in which the format items have been replaced by the string
representation of the corresponding objects in args.
Exceptions:
System.ArgumentNullException:
format or args is null.
System.FormatException:
format is invalid.-or- The index of a format item is less than zero, or greater
than or equal to the length of the args array.
public static string Format (IFormatProvider provider, string format, object arg0);
Parameters:
provider:
An object that supplies culture-specific formatting information.
format:
A composite format string.
arg0:
The object to format.
Exceptions:
A copy of format in which the format item or items have been replaced by
the string representation of arg0.
Exceptions:
System.ArgumentNullException:
format or arg0 is null.
System.FormatException:
format is invalid.-or- The index of a format item is less than zero, or greater
than or equal to one.
public static string Format (IFormatProvider provider, string format, params object[] args);
Parameters:
provider:
An object that supplies culture-specific formatting information.
format:
A composite format string.
args:
An object array that contains zero or more objects to format.
Exceptions:
A copy of format in which the format items have been replaced by the string
representation of the corresponding objects in args.
Exceptions:
System.ArgumentNullException:
format or args is null.
System.FormatException:
format is invalid.-or- The index of a format item is less than zero, or greater
than or equal to the length of the args array.
public static string Format (string format, object arg0, object arg1);
Parameters:
format:
A composite format string.
arg0:
The first object to format.
arg1:
The second object to format.
Exceptions:
A copy of format in which format items are replaced by the string representations
of arg0 and arg1.
Exceptions:
System.ArgumentNullException:
format is null.
System.FormatException:
format is invalid.-or- The index of a format item is not zero or one.
public static string Format (IFormatProvider provider, string format, object arg0, object arg1);
Parameters:
provider:
An object that supplies culture-specific formatting information.
format:
A composite format string.
arg0:
The first object to format.
arg1:
The second object to format.
Exceptions:
A copy of format in which format items are replaced by the string representations
of arg0 and arg1.
Exceptions:
System.ArgumentNullException:
format, arg0, or arg1 is null.
System.FormatException:
format is invalid.-or- The index of a format item is less than zero, or greater
than or equal to two.
public static string Format (string format, object arg0, object arg1, object arg2);
Parameters:
format:
A composite format string.
arg0:
The first object to format.
arg1:
The second object to format.
arg2:
The third object to format.
Exceptions:
A copy of format in which the format items have been replaced by the string
representations of arg0, arg1, and arg2.
Exceptions:
System.ArgumentNullException:
format is null.
System.FormatException:
format is invalid.-or- The index of a format item is less than zero, or greater
than two.
public static string Format (IFormatProvider provider, string format, object arg0, object arg1, object arg2);
Parameters:
provider:
An object that supplies culture-specific formatting information.
format:
A composite format string.
arg0:
The first object to format.
arg1:
The second object to format.
arg2:
The third object to format.
Exceptions:
A copy of format in which the format items have been replaced by the string
representations of arg0, arg1, and arg2.
Exceptions:
System.ArgumentNullException:
format, arg0, arg1, or arg2 is null.
System.FormatException:
format is invalid.-or- The index of a format item is less than zero, or greater
than or equal to three.
public CharEnumerator GetEnumerator ();
public override int GetHashCode ();
public TypeCode GetTypeCode ();
public int IndexOf (char value);
Parameters:
value:
A Unicode character to seek.
Exceptions:
The zero-based index position of value if that character is found, or -1
if it is not.
public int IndexOf (string value);
Parameters:
value:
The string to seek.
Exceptions:
The zero-based index position of value if that string is found, or -1 if
it is not. If value is System.String.Empty, the return value is 0.
Exceptions:
System.ArgumentNullException:
value is null.
public int IndexOf (char value, int startIndex);
Parameters:
value:
A Unicode character to seek.
startIndex:
The search starting position.
Exceptions:
The zero-based index position of value if that character is found, or -1
if it is not.
Exceptions:
System.ArgumentOutOfRangeException:
startIndex is less than 0 (zero) or greater than the length of the string.
public int IndexOf (string value, int startIndex);
Parameters:
value:
The string to seek.
startIndex:
The search starting position.
Exceptions:
The zero-based index position of value if that string is found, or -1 if
it is not. If value is System.String.Empty, the return value is startIndex.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
startIndex is less than 0 (zero) or greater than the length of this string.
public int IndexOf (string value, StringComparison comparisonType);
Parameters:
value:
The string to seek.
comparisonType:
One of the enumeration values that specifies the rules for the search.
Exceptions:
The index position of the value parameter if that string is found, or -1
if it is not. If value is System.String.Empty, the return value is 0.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentException:
comparisonType is not a valid System.StringComparison value.
public int IndexOf (char value, int startIndex, int count);
Parameters:
value:
A Unicode character to seek.
startIndex:
The search starting position.
count:
The number of character positions to examine.
Exceptions:
The zero-based index position of value if that character is found, or -1
if it is not.
Exceptions:
System.ArgumentOutOfRangeException:
count or startIndex is negative.-or- startIndex is greater than the length
of this string.-or-count is greater than the length of this string minus
startIndex.
public int IndexOf (string value, int startIndex, int count);
Parameters:
value:
The string to seek.
startIndex:
The search starting position.
count:
The number of character positions to examine.
Exceptions:
The zero-based index position of value if that string is found, or -1 if
it is not. If value is System.String.Empty, the return value is startIndex.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
count or startIndex is negative.-or- startIndex is greater than the length
of this string.-or-count is greater than the length of this string minus
startIndex.
public int IndexOf (string value, int startIndex, StringComparison comparisonType);
Parameters:
value:
The string to seek.
startIndex:
The search starting position.
comparisonType:
One of the enumeration values that specifies the rules for the search.
Exceptions:
The zero-based index position of the value parameter if that string is found,
or -1 if it is not. If value is System.String.Empty, the return value is
startIndex.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
startIndex is less than 0 (zero) or greater than the length of this string.
System.ArgumentException:
comparisonType is not a valid System.StringComparison value.
public int IndexOf (string value, int startIndex, int count, StringComparison comparisonType);
Parameters:
value:
The string to seek.
startIndex:
The search starting position.
count:
The number of character positions to examine.
comparisonType:
One of the enumeration values that specifies the rules for the search.
Exceptions:
The zero-based index position of the value parameter if that string is found,
or -1 if it is not. If value is System.String.Empty, the return value is
startIndex.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
count or startIndex is negative.-or- startIndex is greater than the length
of this instance.-or-count is greater than the length of this string minus
startIndex.
System.ArgumentException:
comparisonType is not a valid System.StringComparison value.
public int IndexOfAny (char[] anyOf);
Parameters:
anyOf:
A Unicode character array containing one or more characters to seek.
Exceptions:
The zero-based index position of the first occurrence in this instance where
any character in anyOf was found; -1 if no character in anyOf was found.
Exceptions:
System.ArgumentNullException:
anyOf is null.
public int IndexOfAny (char[] anyOf, int startIndex);
Parameters:
anyOf:
A Unicode character array containing one or more characters to seek.
startIndex:
The search starting position.
Exceptions:
The zero-based index position of the first occurrence in this instance where
any character in anyOf was found; -1 if no character in anyOf was found.
Exceptions:
System.ArgumentNullException:
anyOf is null.
System.ArgumentOutOfRangeException:
startIndex is negative.-or- startIndex is greater than the number of characters
in this instance.
public int IndexOfAny (char[] anyOf, int startIndex, int count);
Parameters:
anyOf:
A Unicode character array containing one or more characters to seek.
startIndex:
The search starting position.
count:
The number of character positions to examine.
Exceptions:
The zero-based index position of the first occurrence in this instance where
any character in anyOf was found; -1 if no character in anyOf was found.
Exceptions:
System.ArgumentNullException:
anyOf is null.
System.ArgumentOutOfRangeException:
count or startIndex is negative.-or- count + startIndex is greater than the
number of characters in this instance.
public string Insert (int startIndex, string value);
Parameters:
startIndex:
The zero-based index position of the insertion.
value:
The string to insert.
Exceptions:
A new string that is equivalent to this instance, but with value inserted
at position startIndex.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
startIndex is negative or greater than the length of this instance.
public static string Intern (string str);
Parameters:
str:
A string to search for in the intern pool.
Exceptions:
The system’s reference to str, if it is interned; otherwise, a new reference
to a string with the value of str.
Exceptions:
System.ArgumentNullException:
str is null.
public static string IsInterned (string str);
Parameters:
str:
The string to search for in the intern pool.
Exceptions:
A reference to str if it is in the common language runtime intern pool; otherwise,
null.
Exceptions:
System.ArgumentNullException:
str is null.
public bool IsNormalized ();
Exceptions:
true if this string is in normalization form C; otherwise, false.
Exceptions:
System.ArgumentException:
The current instance contains invalid Unicode characters.
public bool IsNormalized (NormalizationForm normalizationForm);
Parameters:
normalizationForm:
A Unicode normalization form.
Exceptions:
true if this string is in the normalization form specified by the normalizationForm
parameter; otherwise, false.
Exceptions:
System.ArgumentException:
The current instance contains invalid Unicode characters.
public static bool IsNullOrEmpty (string value);
Parameters:
value:
The string to test.
Exceptions:
true if the value parameter is null or an empty string («»); otherwise, false.
public static bool IsNullOrWhiteSpace (string value);
Parameters:
value:
The string to test.
Exceptions:
true if the value parameter is null or System.String.Empty, or if value consists
exclusively of white-space characters.
public static string Join (string separator, IEnumerable<string> values);
Parameters:
separator:
The string to use as a separator. separator is included in the returned string
only if values has more than one element.
values:
A collection that contains the strings to concatenate.
Exceptions:
A string that consists of the members of values delimited by the separator
string. If values has no members, the method returns System.String.Empty.
Exceptions:
System.ArgumentNullException:
values is null.
public static string Join<T> (string separator, IEnumerable<T> values);
Parameters:
separator:
The string to use as a separator. separator is included in the returned string
only if values has more than one element.
values:
A collection that contains the objects to concatenate.
Type parameters:
T:
The type of the members of values.
Exceptions:
A string that consists of the members of values delimited by the separator
string. If values has no members, the method returns System.String.Empty.
Exceptions:
System.ArgumentNullException:
values is null.
public static string Join (string separator, params object[] values);
Parameters:
separator:
The string to use as a separator. separator is included in the returned string
only if values has more than one element.
values:
An array that contains the elements to concatenate.
Exceptions:
A string that consists of the elements of values delimited by the separator
string. If values is an empty array, the method returns System.String.Empty.
Exceptions:
System.ArgumentNullException:
values is null.
public static string Join (string separator, params string[] value);
Parameters:
separator:
The string to use as a separator. separator is included in the returned string
only if value has more than one element.
value:
An array that contains the elements to concatenate.
Exceptions:
A string that consists of the elements in value delimited by the separator
string. If value is an empty array, the method returns System.String.Empty.
Exceptions:
System.ArgumentNullException:
value is null.
public static string Join (string separator, string[] value, int startIndex, int count);
Parameters:
separator:
The string to use as a separator. separator is included in the returned string
only if value has more than one element.
value:
An array that contains the elements to concatenate.
startIndex:
The first element in value to use.
count:
The number of elements of value to use.
Exceptions:
A string that consists of the strings in value delimited by the separator
string. -or-System.String.Empty if count is zero, value has no elements,
or separator and all the elements of value are System.String.Empty.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
startIndex or count is less than 0.-or- startIndex plus count is greater
than the number of elements in value.
System.OutOfMemoryException:
Out of memory.
public int LastIndexOf (char value);
Parameters:
value:
The Unicode character to seek.
Exceptions:
The zero-based index position of value if that character is found, or -1
if it is not.
public int LastIndexOf (string value);
Parameters:
value:
The string to seek.
Exceptions:
The zero-based starting index position of value if that string is found,
or -1 if it is not. If value is System.String.Empty, the return value is
the last index position in this instance.
Exceptions:
System.ArgumentNullException:
value is null.
public int LastIndexOf (char value, int startIndex);
Parameters:
value:
The Unicode character to seek.
startIndex:
The starting position of the search. The search proceeds from startIndex
toward the beginning of this instance.
Exceptions:
The zero-based index position of value if that character is found, or -1
if it is not found or if the current instance equals System.String.Empty.
Exceptions:
System.ArgumentOutOfRangeException:
The current instance does not equal System.String.Empty, and startIndex is
less than zero or greater than or equal to the length of this instance.
public int LastIndexOf (string value, int startIndex);
Parameters:
value:
The string to seek.
startIndex:
The search starting position. The search proceeds from startIndex toward
the beginning of this instance.
Exceptions:
The zero-based starting index position of value if that string is found,
or -1 if it is not found or if the current instance equals System.String.Empty.
If value is System.String.Empty, the return value is the smaller of startIndex
and the last index position in this instance.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
The current instance does not equal System.String.Empty, and startIndex is
less than zero or greater than the length of the current instance. -or-The
current instance equals System.String.Empty, and startIndex is less than
-1 or greater than zero.
public int LastIndexOf (string value, StringComparison comparisonType);
Parameters:
value:
The string to seek.
comparisonType:
One of the enumeration values that specifies the rules for the search.
Exceptions:
The zero-based starting index position of the value parameter if that string
is found, or -1 if it is not. If value is System.String.Empty, the return
value is the last index position in this instance.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentException:
comparisonType is not a valid System.StringComparison value.
public int LastIndexOf (char value, int startIndex, int count);
Parameters:
value:
The Unicode character to seek.
startIndex:
The starting position of the search. The search proceeds from startIndex
toward the beginning of this instance.
count:
The number of character positions to examine.
Exceptions:
The zero-based index position of value if that character is found, or -1
if it is not found or if the current instance equals System.String.Empty.
Exceptions:
System.ArgumentOutOfRangeException:
The current instance does not equal System.String.Empty, and startIndex is
less than zero or greater than or equal to the length of this instance.-or-The
current instance does not equal System.String.Empty, and startIndex — count
+ 1 is less than zero.
public int LastIndexOf (string value, int startIndex, int count);
Parameters:
value:
The string to seek.
startIndex:
The search starting position. The search proceeds from startIndex toward
the beginning of this instance.
count:
The number of character positions to examine.
Exceptions:
The zero-based starting index position of value if that string is found,
or -1 if it is not found or if the current instance equals System.String.Empty.
If value is System.String.Empty, the return value is the smaller of startIndex
and the last index position in this instance.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
count is negative.-or-The current instance does not equal System.String.Empty,
and startIndex is negative.-or- The current instance does not equal System.String.Empty,
and startIndex is greater than the length of this instance.-or-The current
instance does not equal System.String.Empty, and startIndex — count + 1 specifies
a position that is not within this instance. -or-The current instance equals
System.String.Empty and start is less than -1 or greater than zero. -or-The
current instance equals System.String.Empty and count is greater than 1.
public int LastIndexOf (string value, int startIndex, StringComparison comparisonType);
Parameters:
value:
The string to seek.
startIndex:
The search starting position. The search proceeds from startIndex toward
the beginning of this instance.
comparisonType:
One of the enumeration values that specifies the rules for the search.
Exceptions:
The zero-based starting index position of the value parameter if that string
is found, or -1 if it is not found or if the current instance equals System.String.Empty.
If value is System.String.Empty, the return value is the smaller of startIndex
and the last index position in this instance.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
The current instance does not equal System.String.Empty, and startIndex is
less than zero or greater than the length of the current instance. -or-The
current instance equals System.String.Empty, and startIndex is less than
-1 or greater than zero.
System.ArgumentException:
comparisonType is not a valid System.StringComparison value.
public int LastIndexOf (string value, int startIndex, int count, StringComparison comparisonType);
Parameters:
value:
The string to seek.
startIndex:
The search starting position. The search proceeds from startIndex toward
the beginning of this instance.
count:
The number of character positions to examine.
comparisonType:
One of the enumeration values that specifies the rules for the search.
Exceptions:
The zero-based starting index position of the value parameter if that string
is found, or -1 if it is not found or if the current instance equals System.String.Empty.
If value is System.String.Empty, the return value is the smaller of startIndex
and the last index position in this instance.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentOutOfRangeException:
count is negative.-or-The current instance does not equal System.String.Empty,
and startIndex is negative.-or- The current instance does not equal System.String.Empty,
and startIndex is greater than the length of this instance.-or-The current
instance does not equal System.String.Empty, and startIndex + 1 — count specifies
a position that is not within this instance. -or-The current instance equals
System.String.Empty and start is less than -1 or greater than zero. -or-The
current instance equals System.String.Empty and count is greater than 1.
System.ArgumentException:
comparisonType is not a valid System.StringComparison value.
public int LastIndexOfAny (char[] anyOf);
Parameters:
anyOf:
A Unicode character array containing one or more characters to seek.
Exceptions:
The index position of the last occurrence in this instance where any character
in anyOf was found; -1 if no character in anyOf was found.
Exceptions:
System.ArgumentNullException:
anyOf is null.
public int LastIndexOfAny (char[] anyOf, int startIndex);
Parameters:
anyOf:
A Unicode character array containing one or more characters to seek.
startIndex:
The search starting position. The search proceeds from startIndex toward
the beginning of this instance.
Exceptions:
The index position of the last occurrence in this instance where any character
in anyOf was found; -1 if no character in anyOf was found or if the current
instance equals System.String.Empty.
Exceptions:
System.ArgumentNullException:
anyOf is null.
System.ArgumentOutOfRangeException:
The current instance does not equal System.String.Empty, and startIndex specifies
a position that is not within this instance.
public int LastIndexOfAny (char[] anyOf, int startIndex, int count);
Parameters:
anyOf:
A Unicode character array containing one or more characters to seek.
startIndex:
The search starting position. The search proceeds from startIndex toward
the beginning of this instance.
count:
The number of character positions to examine.
Exceptions:
The index position of the last occurrence in this instance where any character
in anyOf was found; -1 if no character in anyOf was found or if the current
instance equals System.String.Empty.
Exceptions:
System.ArgumentNullException:
anyOf is null.
System.ArgumentOutOfRangeException:
The current instance does not equal System.String.Empty, and count or startIndex
is negative.-or- The current instance does not equal System.String.Empty,
and startIndex minus count + 1 is less than zero.
public string Normalize ();
Exceptions:
A new, normalized string whose textual value is the same as this string,
but whose binary representation is in normalization form C.
Exceptions:
System.ArgumentException:
The current instance contains invalid Unicode characters.
public string Normalize (NormalizationForm normalizationForm);
Parameters:
normalizationForm:
A Unicode normalization form.
Exceptions:
A new string whose textual value is the same as this string, but whose binary
representation is in the normalization form specified by the normalizationForm
parameter.
Exceptions:
System.ArgumentException:
The current instance contains invalid Unicode characters.
public string PadLeft (int totalWidth);
Parameters:
totalWidth:
The number of characters in the resulting string, equal to the number of
original characters plus any additional padding characters.
Exceptions:
A new string that is equivalent to this instance, but right-aligned and padded
on the left with as many spaces as needed to create a length of totalWidth.
However, if totalWidth is less than the length of this instance, the method
returns a reference to the existing instance. If totalWidth is equal to the
length of this instance, the method returns a new string that is identical
to this instance.
Exceptions:
System.ArgumentOutOfRangeException:
totalWidth is less than zero.
public string PadLeft (int totalWidth, char paddingChar);
Parameters:
totalWidth:
The number of characters in the resulting string, equal to the number of
original characters plus any additional padding characters.
paddingChar:
A Unicode padding character.
Exceptions:
A new string that is equivalent to this instance, but right-aligned and padded
on the left with as many paddingChar characters as needed to create a length
of totalWidth. However, if totalWidth is less than the length of this instance,
the method returns a reference to the existing instance. If totalWidth is
equal to the length of this instance, the method returns a new string that
is identical to this instance.
Exceptions:
System.ArgumentOutOfRangeException:
totalWidth is less than zero.
public string PadRight (int totalWidth);
Parameters:
totalWidth:
The number of characters in the resulting string, equal to the number of
original characters plus any additional padding characters.
Exceptions:
A new string that is equivalent to this instance, but left-aligned and padded
on the right with as many spaces as needed to create a length of totalWidth.
However, if totalWidth is less than the length of this instance, the method
returns a reference to the existing instance. If totalWidth is equal to the
length of this instance, the method returns a new string that is identical
to this instance.
Exceptions:
System.ArgumentOutOfRangeException:
totalWidth is less than zero.
public string PadRight (int totalWidth, char paddingChar);
Parameters:
totalWidth:
The number of characters in the resulting string, equal to the number of
original characters plus any additional padding characters.
paddingChar:
A Unicode padding character.
Exceptions:
A new string that is equivalent to this instance, but left-aligned and padded
on the right with as many paddingChar characters as needed to create a length
of totalWidth. However, if totalWidth is less than the length of this instance,
the method returns a reference to the existing instance. If totalWidth is
equal to the length of this instance, the method returns a new string that
is identical to this instance.
Exceptions:
System.ArgumentOutOfRangeException:
totalWidth is less than zero.
public string Remove (int startIndex);
Parameters:
startIndex:
The zero-based position to begin deleting characters.
Exceptions:
A new string that is equivalent to this string except for the removed characters.
Exceptions:
System.ArgumentOutOfRangeException:
startIndex is less than zero.-or- startIndex specifies a position that is
not within this string.
public string Remove (int startIndex, int count);
Parameters:
startIndex:
The zero-based position to begin deleting characters.
count:
The number of characters to delete.
Exceptions:
A new string that is equivalent to this instance except for the removed characters.
Exceptions:
System.ArgumentOutOfRangeException:
Either startIndex or count is less than zero.-or- startIndex plus count specify
a position outside this instance.
public string Replace (char oldChar, char newChar);
Parameters:
oldChar:
The Unicode character to be replaced.
newChar:
The Unicode character to replace all occurrences of oldChar.
Exceptions:
A string that is equivalent to this instance except that all instances of
oldChar are replaced with newChar. If oldChar is not found in the current
instance, the method returns the current instance unchanged.
public string Replace (string oldValue, string newValue);
Parameters:
oldValue:
The string to be replaced.
newValue:
The string to replace all occurrences of oldValue.
Exceptions:
A string that is equivalent to the current string except that all instances
of oldValue are replaced with newValue. If oldValue is not found in the current
instance, the method returns the current instance unchanged.
Exceptions:
System.ArgumentNullException:
oldValue is null.
System.ArgumentException:
oldValue is the empty string («»).
public string[] Split (params char[] separator);
Parameters:
separator:
A character array that delimits the substrings in this string, an empty array
that contains no delimiters, or null.
Exceptions:
An array whose elements contain the substrings from this instance that are
delimited by one or more characters in separator. For more information, see
the Remarks section.
public string[] Split (char[] separator, int count);
Parameters:
separator:
A character array that delimits the substrings in this string, an empty array
that contains no delimiters, or null.
count:
The maximum number of substrings to return.
Exceptions:
An array whose elements contain the substrings in this instance that are
delimited by one or more characters in separator. For more information, see
the Remarks section.
Exceptions:
System.ArgumentOutOfRangeException:
count is negative.
public string[] Split (char[] separator, StringSplitOptions options);
Parameters:
separator:
A character array that delimits the substrings in this string, an empty array
that contains no delimiters, or null.
options:
System.StringSplitOptions.RemoveEmptyEntries to omit empty array elements
from the array returned; or System.StringSplitOptions.None to include empty
array elements in the array returned.
Exceptions:
An array whose elements contain the substrings in this string that are delimited
by one or more characters in separator. For more information, see the Remarks
section.
Exceptions:
System.ArgumentException:
options is not one of the System.StringSplitOptions values.
public string[] Split (string[] separator, StringSplitOptions options);
Parameters:
separator:
A string array that delimits the substrings in this string, an empty array
that contains no delimiters, or null.
options:
System.StringSplitOptions.RemoveEmptyEntries to omit empty array elements
from the array returned; or System.StringSplitOptions.None to include empty
array elements in the array returned.
Exceptions:
An array whose elements contain the substrings in this string that are delimited
by one or more strings in separator. For more information, see the Remarks
section.
Exceptions:
System.ArgumentException:
options is not one of the System.StringSplitOptions values.
public string[] Split (char[] separator, int count, StringSplitOptions options);
Parameters:
separator:
A character array that delimits the substrings in this string, an empty array
that contains no delimiters, or null.
count:
The maximum number of substrings to return.
options:
System.StringSplitOptions.RemoveEmptyEntries to omit empty array elements
from the array returned; or System.StringSplitOptions.None to include empty
array elements in the array returned.
Exceptions:
An array whose elements contain the substrings in this string that are delimited
by one or more characters in separator. For more information, see the Remarks
section.
Exceptions:
System.ArgumentOutOfRangeException:
count is negative.
System.ArgumentException:
options is not one of the System.StringSplitOptions values.
public string[] Split (string[] separator, int count, StringSplitOptions options);
Parameters:
separator:
A string array that delimits the substrings in this string, an empty array
that contains no delimiters, or null.
count:
The maximum number of substrings to return.
options:
System.StringSplitOptions.RemoveEmptyEntries to omit empty array elements
from the array returned; or System.StringSplitOptions.None to include empty
array elements in the array returned.
Exceptions:
An array whose elements contain the substrings in this string that are delimited
by one or more strings in separator. For more information, see the Remarks
section.
Exceptions:
System.ArgumentOutOfRangeException:
count is negative.
System.ArgumentException:
options is not one of the System.StringSplitOptions values.
public bool StartsWith (string value);
Parameters:
value:
The string to compare.
Exceptions:
true if value matches the beginning of this string; otherwise, false.
Exceptions:
System.ArgumentNullException:
value is null.
public bool StartsWith (string value, StringComparison comparisonType);
Parameters:
value:
The string to compare.
comparisonType:
One of the enumeration values that determines how this string and value are
compared.
Exceptions:
true if this instance begins with value; otherwise, false.
Exceptions:
System.ArgumentNullException:
value is null.
System.ArgumentException:
comparisonType is not a System.StringComparison value.
public bool StartsWith (string value, bool ignoreCase, CultureInfo culture);
Parameters:
value:
The string to compare.
ignoreCase:
true to ignore case during the comparison; otherwise, false.
culture:
Cultural information that determines how this string and value are compared.
If culture is null, the current culture is used.
Exceptions:
true if the value parameter matches the beginning of this string; otherwise,
false.
Exceptions:
System.ArgumentNullException:
value is null.
public string Substring (int startIndex);
Parameters:
startIndex:
The zero-based starting character position of a substring in this instance.
Exceptions:
A string that is equivalent to the substring that begins at startIndex in
this instance, or System.String.Empty if startIndex is equal to the length
of this instance.
Exceptions:
System.ArgumentOutOfRangeException:
startIndex is less than zero or greater than the length of this instance.
public string Substring (int startIndex, int length);
Parameters:
startIndex:
The zero-based starting character position of a substring in this instance.
length:
The number of characters in the substring.
Exceptions:
A string that is equivalent to the substring of length length that begins
at startIndex in this instance, or System.String.Empty if startIndex is equal
to the length of this instance and length is zero.
Exceptions:
System.ArgumentOutOfRangeException:
startIndex plus length indicates a position not within this instance.-or-
startIndex or length is less than zero.
public char[] ToCharArray ();
public char[] ToCharArray (int startIndex, int length);
Parameters:
startIndex:
The starting position of a substring in this instance.
length:
The length of the substring in this instance.
Exceptions:
A Unicode character array whose elements are the length number of characters
in this instance starting from character position startIndex.
Exceptions:
System.ArgumentOutOfRangeException:
startIndex or length is less than zero.-or- startIndex plus length is greater
than the length of this instance.
public string ToLower ();
public string ToLower (CultureInfo culture);
Parameters:
culture:
An object that supplies culture-specific casing rules.
Exceptions:
The lowercase equivalent of the current string.
Exceptions:
System.ArgumentNullException:
culture is null.
public string ToLowerInvariant ();
public override string ToString ();
public string ToString (IFormatProvider provider);
Parameters:
provider:
(Reserved) An object that supplies culture-specific formatting information.
Exceptions:
The current string.
public string ToUpper ();
public string ToUpper (CultureInfo culture);
Parameters:
culture:
An object that supplies culture-specific casing rules.
Exceptions:
The uppercase equivalent of the current string.
Exceptions:
System.ArgumentNullException:
culture is null.
public string ToUpperInvariant ();
public string Trim ();
public string Trim (params char[] trimChars);
Parameters:
trimChars:
An array of Unicode characters to remove, or null.
Exceptions:
The string that remains after all occurrences of the characters in the trimChars
parameter are removed from the start and end of the current string. If trimChars
is null or an empty array, white-space characters are removed instead. If
no characters can be trimmed from the current instance, the method returns
the current instance unchanged.
public string TrimEnd (params char[] trimChars);
Parameters:
trimChars:
An array of Unicode characters to remove, or null.
Exceptions:
The string that remains after all occurrences of the characters in the trimChars
parameter are removed from the end of the current string. If trimChars is
null or an empty array, Unicode white-space characters are removed instead.
If no characters can be trimmed from the current instance, the method returns
the current instance unchanged.
public string TrimStart (params char[] trimChars);
Parameters:
trimChars:
An array of Unicode characters to remove, or null.
Exceptions:
The string that remains after all occurrences of characters in the trimChars
parameter are removed from the start of the current string. If trimChars
is null or an empty array, white-space characters are removed instead.