كيفية القيام بما يلي: تعديل محتويات السلاسل الحرفية (دليل البرمجة لـ #C)

لأن السلاسل الحرفية قابلة للتغيير لا يمكن (دون استخدام التعليمات البرمجية الغير آمنة) تعديل قيمة كائن السلسلة بعد إنشاؤه. ومع ذلك، توجد عدة طرق لتعديل قيمة السلسلة النصية وتخزين الناتج في كائن سلسلة جديدة. توفر الفئة System.String أساليب تعمل على سلسلة مدخلة وترجع كائن سلسلة جديد. في كثير من الحالات، يمكنك تعيين الكائن الجديد لمتغير السلسلة الحرفية الأصلي. توفر الفئة System.Text.RegularExpressions.Regex طرق إضافية تعمل بطريقة مشابهة. توفر الفئة System.Text.StringBuilder مخزن مؤقت حرفي يمكنك تعديله "في نفس المكان." يستدعي أسلوب StringBuilder.ToString لإنشاء كائن سلسلة جديد يحتوي على محتويات الاحتياطي الحالي.

مثال

يظهر المثال التالي عدة طرق لاستبدال أو لإزالة سلاسل فرعية في سلسلة حرفية محددة.

class ReplaceSubstrings
{
    string searchFor;
    string replaceWith;

    static void Main(string[] args)
    {

        ReplaceSubstrings app = new ReplaceSubstrings();
        string s = "The mountains are behind the clouds today.";

        // Replace one substring with another with String.Replace.
        // Only exact matches are supported.
        s = s.Replace("mountains", "peaks");
        Console.WriteLine(s);
        // Output: The peaks are behind the clouds today.

        // Use Regex.Replace for more flexibility. 
        // Replace "the" or "The" with "many" or "Many".
        // using System.Text.RegularExpressions
        app.searchFor = "the"; // A very simple regular expression.
        app.replaceWith = "many";
        s = Regex.Replace(s, app.searchFor, app.ReplaceMatchCase, RegexOptions.IgnoreCase);
        Console.WriteLine(s);
        // Output: Many peaks are behind many clouds today.

        // Replace all occurrences of one char with another.
        s = s.Replace(' ', '_');
        Console.WriteLine(s);
        // Output: Many_peaks_are_behind_many_clouds_today.

        // Remove a substring from the middle of the string.
        string temp = "many_";
        int i = s.IndexOf(temp);
        if (i >= 0)
        {
            s = s.Remove(i, temp.Length);
        }
        Console.WriteLine(s);
        // Output: Many_peaks_are_behind_clouds_today.

        // Remove trailing and leading whitespace.
        // See also the TrimStart and TrimEnd methods.
        string s2 = "    I'm wider than I need to be.      ";
        // Store the results in a new string variable.
        temp = s2.Trim();
        Console.WriteLine(temp);
        // Output: I'm wider than I need to be.

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    // Custom match method called by Regex.Replace
    // using System.Text.RegularExpressions
    string ReplaceMatchCase(Match m)
    {
        // Test whether the match is capitalized
        if (Char.IsUpper(m.Value[0]) == true)
        {
            // Capitalize the replacement string
            // using System.Text;
            StringBuilder sb = new StringBuilder(replaceWith);
            sb[0] = (Char.ToUpper(sb[0]));
            return sb.ToString();
        }
        else
        {
            return replaceWith;
        }
    }
}

للوصول إلى أحرف مفردة في سلسلة باستخدام منهج الصفيف, يمكنك استخدام كائن StringBuilder الذي يقوم بالتحميل الزائد لعامل التشغيل [] لتوفير وصول إلى احتياطي أحرف داخلية. يمكنك أيضاً تحويل السلسلة إلى صفيف الأحرف باستخدام الأسلوب ToCharArray. يستخدم المثال التالي ToCharArray لإنشاء الصفيف. ثم يتم تعديل بعض العناصر من هذا الصفيف. ثم يتم استدعاء الدالة الإنشائية للسلسلة الحرفية التي تأخذ صفيف من الأحرف كمعلمة إدخال لإنشاء سلسلة حرفية جديدة.

class ModifyStrings
{
    static void Main()
    {
        string str = "The quick brown fox jumped over the fence";
        System.Console.WriteLine(str);

        char[] chars = str.ToCharArray();
        int animalIndex = str.IndexOf("fox");
        if (animalIndex != -1)
        {
            chars[animalIndex++] = 'c';
            chars[animalIndex++] = 'a';
            chars[animalIndex] = 't';
        }

        string str2 = new string(chars);
        System.Console.WriteLine(str2);

        // Keep the console window open in debug mode
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
  The quick brown fox jumped over the fence
  The quick brown cat jumped over the fence 
*/

تم توفير المثال التالي للمواقف النادرة جداً التي قد تحتاج إلى تعديل على سلسلة في الموضع باستخدام تعليمات برمجية غير آمنة بطريقة مشابهة لصفائف الأحرف ذات نمط كلغة C. يوضح المثال كيفية الوصول إلى الأحرف الفردية في المكان باستخدام الكلمة الأساسية fixed. كما يوضح أحد التأثيرات الجانبية المحتملة من العمليات الغير آمنة على السلاسل الناتجة عن طريقة تخزين مترجم #C للسلاسل تخزين داخلي. بشكل عام، يجب عدم استخدام هذه التقنية إلا أذا كانت ضرورية.

class UnsafeString
{
    unsafe static void Main(string[] args)
    {
        // Compiler will store (intern) 
        // these strings in same location.
        string s1 = "Hello";
        string s2 = "Hello";

        // Change one string using unsafe code.
        fixed (char* p = s1)
        {
            p[0] = 'C';
        }

        //  Both strings have changed.
        Console.WriteLine(s1);
        Console.WriteLine(s2);

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

}

راجع أيضًا:

المرجع

السلاسل (البرمجة C# إرشادات)

المبادئ

دليل البرمجة لـ #C