مشاركة عبر


كيفية القيام بما يلي: كتابة الأحرف في سلسلة

مثال التعليمات البرمجية التالي يقوم بكتابة عدد معين من الأحرف من مصفوفة حروف إلى سلسلة موجودة, بدءاً من موضع محدد في مصفوفة الحروف. استخدم StringWriter لفعل ذلك , كما هو موضّح أدناه.

مثال

Option Explicit On 
Option Strict On
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() = {" "c, "t"c, "o"c, " "c, "w"c, "r"c, "i"c, "t"c, "e"c, " "c, "t"c, "o"c, "."c}
        ' 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

using System;
using System.IO;
using System.Text;

public class CharsToStr
{
    public static void Main(String[] args)
    {
        // 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();
    }
}

برمجة نشطة

يوضح هذا المثال استخدام StringBuilder لتعديل سلسلة موجودة. لاحظ أن هذا يتطلب إضافية باستخدام إعلان ، حيث أن فئة StringBuilder هي عضو في مساحة الاسم System.Text. أيضاً، بدلاً من تعريف سلسلة و تحويلها إلى مصفوفة أحرف ، هذا مثال لإنشاء مصفوفة أحرف مباشرةً ثم تهيئته تهيئة أولية.

تنتج هذه التعليمات البرمجية المخرج التالي.

Some number of characters to

راجع أيضًا:

المهام

كيفية القيام بما يلي: إنشاء سرد الدليل

كيفية القيام بما يلي: القراءة والكتابة إلى ملف مُنشأ حديثاً

كيفية القيام بما يلي: افتح ثم إلحاق ملف سجل

كيفية القيام بما يلي: قراءة نص من ملف.

كيفية القيام بما يلي: كتابة نص في ملف

كيفية القيام بما يلي: قراءة الأحرف من سلسلة

المرجع

StringWriter

StringWriter.Write

StringBuilder

المبادئ

ملفات I/O الأساسية