Практическое руководство. Запись символов в строку

С помощью приведенного ниже примера кода можно записать определенное количество символов из массива символов в существующую строку, начиная с указанной позиции в этом массиве. Для этого используйте StringWriter, как показано ниже.

Пример

Imports System
Imports System.IO
Imports System.Text

Public Class CharsToStr
    Public Shared Sub Main()
        ' Create an instance of StringBuilder that can then be modified.
        Dim sb As New StringBuilder("Some number of characters")
        ' Define and create an instance of a character array from which
        ' characters will be read into the StringBuilder.
        Dim b() As Char = {" ","t","o"," ","w","r","i","t","e"," ","t","o","."}
        ' Create an instance of StringWriter
        ' and attach it to the StringBuilder.
        Dim sw As New StringWriter(sb)
        ' Write three characters from the array into the StringBuilder.
        sw.Write(b, 0, 3)
        ' Display the output.
        Console.WriteLine(sb)
        ' Close the StringWriter.
        sw.Close()
    End Sub
End Class
Imports System.Text

Module Example
   Public Sub Main()
      Dim sb As New StringBuilder()
      Dim flag As Boolean = True
      Dim spellings() As String = { "recieve", "receeve", "receive" }
      sb.AppendFormat("Which of the following spellings is {0}:", flag)
      sb.AppendLine()
      For ctr As Integer = 0 To spellings.GetUpperBound(0)
         sb.AppendFormat("   {0}. {1}", ctr, spellings(ctr))
         sb.AppendLine()
      Next
      sb.AppendLine()
      Console.WriteLine(sb.ToString())
   End Sub
End Module
' The example displays the following output:
'       Which of the following spellings is True:
'          0. recieve
'          1. receeve
'          2. receive
using System;
using System.IO;
using System.Text;

public class CharsToStr
{
    public static void Main()
    {
        // Create an instance of StringBuilder that can then be modified.
        StringBuilder sb = new StringBuilder("Some number of characters");
        // Define and create an instance of a character array from which
        // characters will be read into the StringBuilder.
        char[] b = {' ','t','o',' ','w','r','i','t','e',' ','t','o','.'};
        // Create an instance of StringWriter
        // and attach it to the StringBuilder.
        StringWriter sw = new StringWriter(sb);
        // Write three characters from the array into the StringBuilder.
        sw.Write(b, 0, 3);
        // Display the output.
        Console.WriteLine(sb);
        // Close the StringWriter.
        sw.Close();
    }
}
using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      StringBuilder sb = new StringBuilder();
      bool flag = true;
      string[] spellings = { "recieve", "receeve", "receive" };
      sb.AppendFormat("Which of the following spellings is {0}:", flag);
      sb.AppendLine();
      for (int ctr = 0; ctr <= spellings.GetUpperBound(0); ctr++) {
         sb.AppendFormat("   {0}. {1}", ctr, spellings[ctr]);
         sb.AppendLine();
      }
      sb.AppendLine();
      Console.WriteLine(sb.ToString());
   }
}
// The example displays the following output:
//       Which of the following spellings is True:
//          0. recieve
//          1. receeve
//          2. receive
using namespace System;
using namespace System::IO;
using namespace System::Text;

public ref class CharsToStr
{
public:
    static void Main()
    {
        // Create an instance of StringBuilder that can then be modified.
        StringBuilder^ sb = gcnew StringBuilder("Some number of characters");
        // Define and create an instance of a character array from which
        // characters will be read into the StringBuilder.
        array<Char>^ b = {' ','t','o',' ','w','r','i','t','e',' ','t','o','.'};
        // Create an instance of StringWriter
        // and attach it to the StringBuilder.
        StringWriter^ sw = gcnew StringWriter(sb);
        // Write three characters from the array into the StringBuilder.
        sw->Write(b, 0, 3);
        // Display the output.
        Console::WriteLine(sb);
        // Close the StringWriter.
        sw->Close();
    }
};

int main()
{
    CharsToStr::Main();
}

Отказоустойчивость

Этот пример иллюстрирует использование StringBuilder для изменения существующей строки. Обратите внимание, что это требует дополнительной декларации using, поскольку класс StringBuilder является членом пространства имен System.Text. Вместо того чтобы определять строку и затем преобразовывать ее в массив символов, с помощью примера можно напрямую создать и инициализировать массив символов.

В результате получаются следующие выходные данные.

Some number of characters to

См. также

Задачи

Практическое руководство. Создание списка каталогов

Практическое руководство. Считывание из нового файла данных и запись в этот файл

Практическое руководство. Открытие файла журнала и добавление в него данных

Практическое руководство. Считывание текста из файла

Практическое руководство. Запись текста в файл

Практическое руководство. Считывание символов из строки

Ссылки

StringWriter

StringWriter.Write

StringBuilder

Основные понятия

Основы файлового ввода-вывода