Руководство C# String и StringBuilder
View more Tutorials:



При работе с текстовыми данными CSharp предоставляет вам 2 класса String и StringBuilder. При работе с большими данными вы должны использовать StringBuilder для эффективной оптимизации. В принципе, эти 2 класса имеют много общего.
- String является неизменяемым (immutable), более подробная информация об этой концепции содержится в статье, и не допускает существования подкласса.
- StringBuilder изменчив (mutable).
Рассмотрим иллюстрированный пример:
MutableClassExample.cs
namespace StringTutorial
{
// Это класс с 1 полем: 'Value'.
// Если у вас есть объект данного класса
// Вы можете прикрепить новое значение для поля 'Value'
// через метод SetNewValue(int).
// Таким образом это изменный класс (mutable).
class MutableClassExample
{
private int Value;
public MutableClassExample(int value)
{
this.Value = value;
}
public void SetNewValue(int newValue)
{
this.Value = newValue;
}
}
}
ImmutableClassExample.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringTutorial
{
// Это класс имеющий 2 поля (field): 'Value' & 'Name'.
// Если вы хотите получить объект данного класса
// Вы не можете прикрепить новое значение для 'Value','Name' снаружи,
// Это значит данный класс является неизменным (immutable)
class ImmutableClassExample
{
private int Value;
private String Name;
public ImmutableClassExample(String name, int value)
{
this.Value = value;
this.Name = name;
}
public String GetName()
{
return Name;
}
public int GetValue()
{
return Value;
}
}
}
String - неизменяемый класс. String включает различные поля, такие как длина (Length), но эти значения не могут быть изменены.
В C# иногда вы видите, что String и string используются параллельно. На самом деле, они не имеют никакой разницы, string может рассматриваться как псевдоним (alias) для System.String (полное имя, включая пространство имен класса String).
В таблице ниже приведен полный список псевдонимов общих классов.
В таблице ниже приведен полный список псевдонимов общих классов.
Alias | Class |
object | System.Object |
string | System.String |
bool | System.Boolean |
byte | System.Byte |
sbyte | System.SByte |
short | System.Int16 |
ushort | System.UInt16 |
int | System.Int32 |
uint | System.UInt32 |
long | System.Int64 |
ulong | System.UInt64 |
float | System.Single |
double | System.Double |
decimal | System.Decimal |
char | System.Char |
String это очень важный в CSharp, и любой, кто начинает с CSharp, использует команду Console.WriteLine(), чтобы распечатать String на экран Console. Многие не имеют понятия, что String является неизменяемым (immutable) и опечатанным (не позволяет иметь подклассы). Каждая модификация в String создает новый String объект.
** String **
[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class String : IComparable, ICloneable, IConvertible,
IEnumerable, IComparable<string>, IEnumerable<char>, IEquatable<string>
Вы можете посмотреть методы String по ссылке:
Ниже приведён список некоторых распространённых методов String:
Some String methods
public bool EndsWith(string value)
public bool EndsWith(string value, StringComparison comparisonType)
public bool Equals(string value)
public int IndexOf(char value)
public int IndexOf(char value, int startIndex)
public int IndexOf(string value, int startIndex, int count)
public int IndexOf(string value, int startIndex, StringComparison comparisonType)
public int IndexOf(string value, StringComparison comparisonType)
public string Insert(int startIndex, string value)
public int LastIndexOf(char value)
public int LastIndexOf(char value, int startIndex)
public int LastIndexOf(char value, int startIndex, int count)
public int LastIndexOf(string value)
public int LastIndexOf(string value, int startIndex)
public int LastIndexOf(string value, int startIndex, int count)
public int LastIndexOf(string value, int startIndex, int count, StringComparison comparisonType)
public int LastIndexOf(string value, int startIndex, StringComparison comparisonType)
public int LastIndexOf(string value, StringComparison comparisonType)
public int LastIndexOfAny(char[] anyOf)
public int LastIndexOfAny(char[] anyOf, int startIndex)
public int LastIndexOfAny(char[] anyOf, int startIndex, int count)
public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType)
public string Replace(char oldChar, char newChar)
public string Replace(string oldValue, string newValue)
public string[] Split(params char[] separator)
public string[] Split(char[] separator, int count)
public string[] Split(char[] separator, int count, StringSplitOptions options)
public string[] Split(char[] separator, StringSplitOptions options)
public string[] Split(string[] separator, StringSplitOptions options)
public bool StartsWith(string value)
public bool StartsWith(string value, bool ignoreCase, CultureInfo culture)
public bool StartsWith(string value, StringComparison comparisonType)
public string Substring(int startIndex)
public string Substring(int startIndex, int length)
public char[] ToCharArray()
public char[] ToCharArray(int startIndex, int length)
public string ToLower()
public string ToLower(CultureInfo culture)
public string ToLowerInvariant()
public override string ToString()
public string ToUpper()
public string ToUpper(CultureInfo culture)
public string ToUpperInvariant()
public string Trim()
public string Trim(params char[] trimChars)
public string TrimEnd(params char[] trimChars)
public string TrimStart(params char[] trimChars)
length (Длина)- это свойство строки (string), она возвращает количество символов Unicode в этой строке.
LengthDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringTutorial
{
class LengthDemo
{
public static void Main(string[] args)
{
String str = "This is text";
// Length является Property (свойством) string.
// Он является длиной строки (количество символов строки).
int len = str.Length;
Console.WriteLine("String Length is : " + len);
Console.Read();
}
}
}
Результаты запуска примера:
String Length is : 12
Concat - это статический метод, который объединяет (concatenate) несколько строк и возвращает новый String.
ConcatDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringTutorial
{
class ConcatDemo
{
public static void Main(string[] args)
{
string s1 = "One";
string s2 = "Two";
string s3 = "Three";
// Похоже на s1 + s2;
string s = String.Concat(s1, s2);
Console.WriteLine("Concat s1, s2 : " + s);
// Похоже на s1 + s2 + s3;
s = String.Concat(s1, s2, s3);
Console.WriteLine("Concat s1, s2, s3 : " + s);
Console.Read();
}
}
}
Результаты запуска примера:
Concat s1, s2 : OneTwo
Concat s1, s2, s3: OneTwoThree
IndexOf(..) это метод возвращающий индекс местоположения определенного символа, который появляется в первый раз или подстрока определенная в текущей строке. Существует 8 методов IndexOf с разными параметрами. Индекс начинается с 0 (Не с 1).

IndexOfDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringTutorial
{
class IndexOfDemo
{
public static void Main(string[] args)
{
String str = "This is text";
// Найти индекс (index) где появляется первый символ 'i'.
int idx = str.IndexOf('i'); // ==> 2
Console.WriteLine("- IndexOf('i') = " + idx);
// Найти индекс (index) где появляется первый символ 'i'.
// считая от 4-го индекса к концу строки.
idx = str.IndexOf('i', 4); // ==> 5
Console.WriteLine("- indexOf('i',4) = " + idx);
// Найти индекс (index) где появляется первая подстрока "te".
idx = str.IndexOf("te"); // ==> 8
Console.WriteLine("- IndexOf('te') = " + idx);
Console.Read();
}
}
}
Результаты выполнения примера:
- IndexOf('i') = 2
- IndexOf('i',4) = 5
- IndexOf('te') = 8

SubstringDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringTutorial
{
class SubstringDemo
{
public static void Main(string[] args)
{
string str = "This is text";
// Возвращает подстроку с индекса 3 до конца строки.
string substr = str.Substring(3);
Console.WriteLine("- Substring(3)=" + substr);
// Возвращает подстроку с индекса 2, и длину 7.
substr = str.Substring(2, 7);
Console.WriteLine("- Substring(2, 7) =" + substr);
Console.Read();
}
}
}
Результаты выполнения примера:
- Substring(3)=s is text
- Substring(2, 7)=is is t
Replace(..): заменяет все подстроки другой подстрокой в текущей строке. Возвращает новую строку (string).
ReplaceDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringTutorial
{
class ReplaceDemo
{
public static void Main(string[] args)
{
String str = "This is text";
// Заменяет все символы 'i' символом 'x'.
String s2 = str.Replace('i', 'x');
Console.WriteLine("- s2=" + s2);// ==> "Thxs xs text".
// Заменяет все подстроки "is" с помощью "abc".
String s3 = str.Replace("is", "abc");
Console.WriteLine("- s3=" + s3);// ==> "Thabc abc text".
// Заменяет все подстроки "is" появляющиеся в первый раз с помощью "abc".
String s4 = ReplaceFirst(str, "is", "abc");
Console.WriteLine("- s4=" + s4);// ==> "Thabc is text".
Console.Read();
}
// Заменяет подстроки появляющиеся в первый раз новой подстрокой.
static string ReplaceFirst(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
}
}
Результаты выполнения примера:
- s2=Thxs xs text
- s3=Thabc abc text
- s4=Thabc is text
StringOtherDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringTutorial
{
class StringOtherDemo
{
public static void Main(string[] args)
{
String str = "This is text";
Console.WriteLine("- str=" + str);
// Возвращает строку со строчными буквами (lower case string).
String s2 = str.ToLower();
Console.WriteLine("- s2=" + s2);
// Возвращает строку с прописными буквами (upper case string).
String s3 = str.ToUpper();
Console.WriteLine("- s3=" + s3);
// Проверить начинается ли строка с подсроки "This" или нет.
bool swith = str.StartsWith("This");
Console.WriteLine("- 'str' startsWith This ? " + swith);
// String с пробелом спереди и сзади.
// \t является символом TAB.
// \n является символом новой строки.
str = " \t CSharp is hot! \t \n ";
Console.WriteLine("- str=" + str);
// Возвращает копию String, убирает пробел с начала и конца строки.
String s4 = str.Trim();
Console.WriteLine("- s4=" + s4);
Console.Read();
}
}
}
Результаты выполнения примера:
- str=This is text
- s2=this is text
- s3=THIS IS TEXT
- 'str' startsWith This ? True
- str= Csharp is hot!
- s4=CSharp is hot!
В C# каждая модификация в результате String создает новый объект String. Между тем StringBuilder содержит в себе массив символов, этот массив будет автоматически заменен на больший массив, если это необходимо, и скопирует символы из старого массива. Если вам необходимо объединить несколько строк много раз, вы должны использовать StringBuilder, это помогает повысить эффективность программы. Но это не обязательно, если вы только объединяете (concatenate) несколько строк, вы не должны злоупотреблять StringBuilder в этом случае.

StringBuilderDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringTutorial
{
class StringBuilderDemo
{
public static void Main(string[] args)
{
// Создать объект StringBuilder
// с объемом (capacity) содержащим 10 символов.
StringBuilder sb = new StringBuilder(10);
// Соединить подстроку.
sb.Append("Hello...");
Console.WriteLine("- sb after appends a string: " + sb);
// Соединить символ.
char c = '!';
sb.Append(c);
Console.WriteLine("- sb after appending a char: " + sb);
// Вставить String в индекс 5.
sb.Insert(8, " CSharp");
Console.WriteLine("- sb after insert string: " + sb);
// Удалить подстроку начиная с индекса 5, с 3 символами.
sb.Remove(5, 3);
Console.WriteLine("- sb after remove: " + sb);
// Получить string в StringBuilder.
String s = sb.ToString();
Console.WriteLine("- String of sb: " + s);
Console.Read();
}
}
}
Результаты выполнения примера:
- sb after appends a string: Hello...
- sb after appending a char: Hello...!
- sb after insert string: Hello... CSharp!
- sb after remove: Hello CSharp!
- String of sb: Hello CSharp!