Объекты класса String объявляются как все прочие объекты простых типов - с явной
или отложенной инициализацией, с явным или неявным вызовом конструктора класса.
Чаще всего, при объявлении строковой переменной конструктор явно не вызывается, а
инициализация задается строковой константой. Но у класса String достаточно много
конструкторов. Они позволяют сконструировать строку из:
Объект world создан без явного вызова конструктора, а объекты sssss, stryes, strye
созданы разными конструкторами класса String.
присваивание (=);
две операции проверки эквивалентности (==) и (!=);
Бинарная операция "+" сцепляет две строки, приписывая вторую строку к хвосту
первой.
Возможность взятия индекса при работе со строками отражает тот приятный факт, что
строку можно рассматривать как массив и получать без труда каждый ее символ.
Каждый символ строки имеет тип char, доступный только для чтения, но не для записи.
Строковые константы
//Неизменяемые значения
s1= "Zenon"; ch1 = s1[0];
//s1[0]='L';
Статические свойства и методы класса String
Метод Format
Здесь строка, задающая первый аргумент метода, помимо обычных символов, содержит
форматы, заключенные в фигурные скобки. В данном примере используется
простейший вид формата - он определяет объект, который должен быть подставлен в
участок строки, занятый данным форматом. Помимо неявных вызовов, нередко
возникает необходимость явного форматирования строки.
Давайте рассмотрим общий синтаксис как самого метода Format, так и используемых в
нем форматов. Метод Format, как и большинство методов, является перегруженным и
может вызываться с разным числом параметров. Первый необязательный параметр
метода задает провайдера, определяющего национальные особенности, которые
используются в процессе форматирования. В качестве такого параметра должен быть
задан объект, реализующий интерфейс System.IFormatProvider. Если этот параметр не
задан, то используется культура, заданная по умолчанию. Вот примеры двух
реализаций этого метода:
{N [,M [:<коды_форматирования>]]}
Методы Join и Split выполняют над строкой текста взаимно обратные преобразования.
Динамический метод Split позволяет осуществить разбор текста на элементы.
Статический метод Join выполняет обратную операцию, собирая строку из элементов.
На вход методу Split передается один или несколько символов, интерпретируемых как
разделители. Объект string, вызвавший метод, разделяется на подстроки,
ограниченные этими разделителями. Из этих подстрок создается массив, возвращаемый
в качестве результата метода. Другая реализация позволяет ограничить число
элементов возвращаемого массива.
Обратите внимание, что методы Split и Join хорошо работают, когда при разборе
используется только один разделитель. В этом случае сборка действительно является
обратной операцией и позволяет восстановить исходную строку. Если же при разборе
задается некоторое множество разделителей, то возникают две проблемы:
Как всегда, есть несколько способов справиться с проблемой. Один из них состоит в
том, чтобы написать собственную реализацию этих функций, другой - в корректировке
полученных результатов, третий - в использовании более мощного аппарата
регулярных выражений, и о нем мы поговорим чуть позже.
public StringBuilder (string str, int cap). Параметр str задает строку
инициализации, cap - емкость объекта;
public StringBuilder (int curcap, int maxcap). Параметры curcap и maxcap
задают начальную и максимальную емкость объекта;
public StringBuilder (string str, int start, int len, int cap).
Параметры str, start, len задают строку инициализации, cap - емкость объекта.
присваивание (=);
две операции проверки эквивалентности (==) и (!=);
Со строкой этого класса можно работать как с массивом, но, в отличие от класса String,
здесь уже все делается как надо: допускается не только чтение отдельного символа, но
и его изменение. Рассмотрим с небольшими модификациями наш старый пример:
Основные методы
У класса StringBuilder методов значительно меньше, чем у класса String. Это и понятно
- класс создавался с целью дать возможность изменять значение строки. По этой
причине у класса есть основные методы, позволяющие выполнять такие операции над
строкой как вставка, удаление и замена подстрок, но нет методов, подобных поиску
вхождения, которые можно выполнять над обычными строками. Технология работы
обычно такова: конструируется строка класса StringBuilder; выполняются операции,
требующие изменение значения; полученная строка преобразуется в строку класса
String; над этой строкой выполняются операции, не требующие изменения значения
строки. Давайте чуть более подробно рассмотрим основные методы класса
StringBuilder:
public StringBuilder Remove (int start, int len). Метод удаляет подстроку
длины len, начинающуюся с позиции start;
В этом фрагменте кода конструируются две строки. Первая из них создается из строк и
булевых значений true и false. Для конструирования используются методы Insert и
Append. Вторая строка конструируется в цикле с применением метода AppendFormat.
Результатом этого конструирования является строка, в которой простые предложения
исходного текста пронумерованы.
Емкость буфера
Каждый экземпляр строки класса StringBuilder имеет буфер, в котором хранится строка.
Объем буфера - его емкость - может меняться в процессе работы со строкой. Объекты
класса имеют две характеристики емкости - текущую и максимальную. В процессе
работы текущая емкость изменяется, естественно, в пределах максимальной емкости,
которая реально достаточно высока. Если размер строки увеличивается, то
соответственно автоматически растет и текущая емкость. Если же размер строки
уменьшается, то емкость буфера остается на том же уровне. По этой причине иногда
разумно уменьшать емкость. Следует помнить, что попытка уменьшить емкость до
величины, меньшей длины строки, приведет к ошибке.
//Емкость буфера
int curvol1 = txtbuild.Capacity;
int curvol2 = strbuild.Capacity;
int maxvol1 = txtbuild.MaxCapacity;
int maxvol2 = strbuild.MaxCapacity;
Console.WriteLine("curvol1= {0}",curvol1);
Console.WriteLine("curvol2= {0}",curvol2);
Console.WriteLine("maxvol1= {0}",maxvol1);
Console.WriteLine("maxvol2= {0}",maxvol2);
int sure1 = txtbuild.EnsureCapacity(100);
int sure2 = strbuild.EnsureCapacity(100);
Console.WriteLine("sure1= {0}",sure1);
Console.WriteLine("sure2= {0}",sure2);
curvol2 = strbuild.Capacity;
Console.WriteLine("curvol2= {0}",curvol2);
//ошибка! попытка установить емкость меньше длины строки
//strbuild.Capacity = 25;
strbuild.Capacity = 256; //так можно!
curvol2 = strbuild.Capacity;
Console.WriteLine("curvol2= {0}",curvol2);
//увеличим строку - емкость увеличится
int len = txtbuild.Length;
txtbuild.Append(txtbuild.ToString());
curvol1 = txtbuild.Capacity;
Console.WriteLine("curvol1= {0}",curvol1);
//уменьшим строку
txtbuild.Remove(len, len);
curvol1 = txtbuild.Capacity;
Console.WriteLine("curvol1= {0}",curvol1);
First, string is a reference type that has a Length property, which returns the number of
characters in its internal buffer. You cannot iterate through every character of a string,
checking for '\0'. Here we see four examples of using the Length property on strings.
The four strings we use are all of different Lengths, and there are variable strings,
constant strings, and literal strings.
using System;
class Program
{
static void Main()
{
// An example string
string a = "One example";
Console.WriteLine(a.Length);
// A constant string
const string c = "Three";
Console.WriteLine(c.Length);
// A literal string
Console.WriteLine("Four".Length);
}
}
11
0
5
4
Description. The final part above shows how you can treat a string literal, contained in
quotation marks, as an object in the C# language. This is a powerful feature and can
help make your code clearer by avoiding magic constants.
Here we see that you must first test for null strings before calling the Length property.
This is because you cannot access members on null reference types. The IsNullOrEmpty
method is ideal for this. Additionally, there are some interesting behaviors with null
strings at the class level.
using System;
class Program
{
static void Main()
{
F(null);
F("cat");
F("book");
F("");
}
True
3
4
True
Microsoft's article on this subject has some interesting details on string Length. It tells
you that the Length is not derived from the number of chars, but not symbolic Unicode
chars.
MSDN: "The Length property returns the number of Char objects in this instance, not
the number of Unicode characters. The reason is that a Unicode character might be
represented by more than one Char." Additionally, null characters may be contained in
the middle of C# strings. This is not a common occurrence in purely managed code,
however.
Visit msdn.microsoft.com.
Caching string Length
Here we explore the idea of caching string Length integers. If you are using a string
thousands of times and accessing the Length property each time, this may be incurring
some overhead.
When accessing string Length, this MSIL instruction will be generated: callvirt
instance int32 [mscorlib]System.String::get_Length(). Next, the value will be retrieved
from an internal part of the .NET runtime.
// Example string
string one = "one" + 1.ToString();
// Cached length
int cl = one.Length;
// A
int len = one.Length;
if (one[len - 1] == 'x')
{
}
// B
if (one[cl - 1] == 'x')
{
}
Summary
The string type in C# provides the Length property, which is very useful for finding the
number of chars in a string. We saw an example of the Length property being used on
four different strings, as well as with null and empty strings. Finally, we found that
hoisting the string Length out of a tight loop can improve performance.
C# String Overview
7-Zip Algorithm Array ASP.NET Attribute Bit Books Bool Buffer Cache Cast Char Class
Collection Compress Console Convert Data DataGridView DateTime Delegate Dictionary
Directive Enum Exception File Format Google HTML If Interface LINQ List Loop Lowercase
Math Memory Method Misc .NET Number Object Path PHP Process Program Random
Reflection Regex SICP Sort Split SQL Static String StringBuilder Struct Switch Thread
TimeSpan Unsafe Variable VB.NET VS Web Forms Whitespace Windows XML
You will find that strings are at the core of almost every C# program, providing a
useful type for character data. We need strings for file IO, for database layers, and for
web pages. Here, we look at the most important methods and properties of the string
type in the C# language.
Introduction
In this simple program, you can see how a string is created and assigned to a string
literal "dot". Then, another string literal is appended to that string. Finally, a method on
the string type is called to manipulate the strings again.
using System;
class Program
{
static void Main()
{
string value = "dot";
value += "net";
string result = string.Concat(value, "perls");
Console.WriteLine(result);
}
}
dotnetperls
Searching strings
The .NET Framework presents several different string searching methods, the most
useful of which is probably IndexOf. There are several variants of IndexOf shown here,
including Contains.
Copying strings
Usually, you will not need to copy strings in your C# programs; you can just assign
references to existing strings. However, these two articles introduce reasons why you
may want to copy strings, and also demonstrate how you can do this.
It is often useful to test only the first or last few characters of a string for a certain
value. The StartsWith and EndsWith methods provide this ability in the C# language, as
demonstrated in the linked articles.
Sometimes, your data may be uppercase when you would rather it be lowercase. You
can invoke the ToLower method to solve this problem, or get the reverse effect with
ToUpper. These tutorials describe aspects of these methods.
See Lowercase/Uppercase.
Whitespace
Also, the C# language and .NET Framework give you many ways to handle whitespace
in your string instances. You can trim strings, pad strings, and use empty and null
strings. These features are described in a separate category on Dot Net Perls.
Concatenating strings
When you concat strings, you put them together into a larger string; when you append
a string, you put it at the end of another string. This site covers concatenating and
appending strings in the C# language in the linked articles.
Joining strings
You can also join together many strings in the C# language. Optionally, you can specify
a delimiter character, which is inserted between all the original strings into the final
string.
You can insert a string at any position in an existing string; you can also remove a
series of characters starting at any position. To do these tasks, please use the Insert or
Remove methods, as shown in the linked articles.
See Insert String Method.
Replacing strings
Your string data may contain a series of characters that you want to replace with
another substring in each place it is found. The Replace method is useful in this case,
and the article here shows you how to use it.
In the C# language, you never need to manually count the number of characters in a
string. Instead, you should access the Length property on a string instance, as the
example given in this article shows.
Getting substrings
You can acquire a substring of any string by using the Substring method. Also, you can
use Substring to truncate or to receive only the right-most part of a string. These
articles demonstrate how you can use this method.
Comparing strings
There are a variety of ways to compare two strings for equality in the C# programming
language. These articles reveal aspects of string comparisons, with the first article
being most useful.
Splitting strings
In programs that process text data, you often need to separate a single string into
many smaller strings based on a delimiter character. You can find lots of information on
Split on this site.
The concept of interning strings is very old and a classic compiler optimization: it
promotes the sharing of common string data resources. These two article discuss ways
that string interning works in the C# language.
ToString
You can convert any variable into its string representation with the ToString method.
These examples deal with the ToString method and a possible optimization you could
use.
Examples
This set of articles describe various ways you can use the string type. You can use the
ref keyword with strings, the static modifier, and also use strings as parameters and
properties. String literals are also very useful.
When a string contains a number in its data, you cannot use that number directly.
Instead, you need to parse it into another data type. This article shows you how you
can do this.
Each string contains data that is made up of individual characters. There are several
ways you deal with these chars, typically by using looping constructs, as we
demonstrate in these tutorials.
In this article, we look at how you can count the number of lines in a string. This can be
done with a loop over the characters and a way to test for newline characters, as the
article shows.
Formatting strings
With the string.Format method, you can use a single method call to concatenate strings
and also format various data types with substitutions. This article provides detailed
information about the string.Format method.
String constructors
Typically, you won't need string constructors in programs, but they can be very useful
in specific situations. This article demonstrates how you can use the various overloads
of the string constructor in the C# language.
Converting strings
There are several different tutorials that focus on how to convert from and to the string
type. We convert character arrays, dictionaries, string arrays, and lists in these articles.
Performance
Strings are actually pretty fast if you know how to use them in the C# language. These
articles show some aspects of string performance; please also check out the
StringBuilder link.