CopyPastehas never been so tasty!

Get Array class elements as string using StringBuilder class

by anonymous

  • 0
  • 0
  • 0
103 views

Get Array class elements as string using StringBuilder class in C#

String Builder ClassA StringBuilder class provides the best way to manipulate the strings. It means that we can insert, append, remove, and replace characterswithout creating a new string every time.The following example illustrates that how to manipulate characters with the StringBuilder class and then place the characters into a String object.Example Code 

static void Main(string[] args)

        {

            String MyName;

            StringBuilder MyOtherName = new StringBuilder("Hello");

MyOtherName.Remove(2, 3); // produces output  "He"

MyOtherName.Insert(2, "lp"); // produces output  "Help"

MyOtherName.Replace('l', 'a'); // produces output  "Heap"

            MyName = MyOtherName.ToString();

        }

 StringBuilder.AppendFormat

 StringBuilder.AppendFormat replaces a format specifier passed in a string with formatted text.The following example uses the AppendFormat method to place an integer value formatted as a currency value at the end of a StringBuilder.Example Code 

intMyInt = 25;

StringBuilder MyStringBuilder = new StringBuilder("Your total is ");

MyStringBuilder.AppendFormat("{0:C} ", MyInt);

Console.WriteLine(MyStringBuilder);

 This example displays Your total is  25.

 Array class elements as string

 The following Code illustrates that how we can get Array class elements as string using StringBuilder class in C#Code

 using System;

 

usingSystem.Collections;

usingSystem.Collections.Generic;

using System.IO;

usingSystem.Text;

usingSystem.Text.RegularExpressions;

 class Program

    {

static void Main(string[] args)

        {

char[] i = { 'A', 'B', 'C', 'D' };

Console.WriteLine(Program.GetArrayContents(i));

 Console.ReadLine();

        }

public static string GetArrayContents(Array Arr)

        {

            StringBuilder result = new StringBuilder("String Form   ");

stringSeperator = ",";

foreach (object Obj in Arr)

            {

result.AppendFormat("{0}{1} ", Obj.ToString(), Seperator);

            }

returnresult.ToString();

}          

 }

Add A Comment: